﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using KL.Store.Data;
using KL.Store.Web.Models;
using KL.Store.Core.Domain;
using KL.Store.Core;
using GittiGidiyor.Product;
using GittiGidiyor;
using GittiGidiyor.Category;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;
using Microsoft.WindowsAzure;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Globalization;
using System.Threading;
using GittiGidiyor;
using GittiGidiyor.Category;

namespace KL.Store.Web.Controllers
{
    public class UploadController : KL.Store.Core.Web.BaseController
    {
        #region Index

        public ActionResult Index()
        {
            return View();
        }

        #endregion

        #region Resize Images

        [HttpPost]
        public ActionResult ResizeImages(string Password)
        {
            if (!string.IsNullOrEmpty(Password))
            {
                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    string path = Server.MapPath("~/Images/");

                    int resimSayisi = 0;
                    int hataliResimSayisi = 0;
                    IList<ProductImage> ProductImages = dbProduct.GetAllImages();
                    foreach (ProductImage productImage in ProductImages)
                    {
                        try
                        {
                            DownloadImage(productImage.ProductId, Parameters.WebSiteImageUrl + "/product-big/" + productImage.ProductId.ToString() + "_" + productImage.ImageId.ToString() + ".jpg", productImage.ImageId);
                            Logger.Write("Image Resized : " + productImage.ProductId.ToString() + "_" + productImage.ImageId.ToString() + ".jpg", "Trace");
                            resimSayisi++;
                        }
                        catch (Exception ex)
                        {
                            Logger.Write(ex, "Exception");
                            hataliResimSayisi++;
                        }
                    }
                    return Content(resimSayisi + " Adet Resim Yeniden Boyutlandi. " + hataliResimSayisi + " Resim Hatali.");
                }
                else
                {
                    return Content("Parametreleri Kontrol Ediniz.");
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region Resize Single Image

        [HttpPost]
        public ActionResult ResizeSingleImage(string Password, int productId)
        {
            if (!string.IsNullOrEmpty(Password))
            {
                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    string path = Server.MapPath("~/Images/");

                    int resimSayisi = 0;
                    int hataliResimSayisi = 0;
                    IList<ProductImage> ProductImages = dbProduct.GetImageList(productId);
                    foreach (ProductImage productImage in ProductImages)
                    {
                        try
                        {
                            DownloadImage(productImage.ProductId, Parameters.WebSiteImageUrl + "/product-big/" + productImage.ProductId.ToString() + "_" + productImage.ImageId.ToString() + ".jpg", productImage.ImageId);
                            Logger.Write("Image Resized : " + productImage.ProductId.ToString() + "_" + productImage.ImageId.ToString() + ".jpg", "Trace");
                            resimSayisi++;
                        }
                        catch (Exception ex)
                        {
                            Logger.Write(ex, "Exception");
                            hataliResimSayisi++;
                        }
                    }
                    return Content(resimSayisi + " Adet Resim Yeniden Boyutlandi. " + hataliResimSayisi + " Resim Hatali.");
                }
                else
                {
                    return Content("Parametreleri Kontrol Ediniz.");
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region Resize Category Images

        [HttpPost]
        public ActionResult ResizeCategoryImages(string Password, int categoryId, int includeSubs)
        {
            if (!string.IsNullOrEmpty(Password))
            {
                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    string path = Server.MapPath("~/Images/");
                    IList<Product> products;
                    if (includeSubs == 1)
                    {
                        products = dbProduct.GetListCatFull(categoryId, 9999, eStoreUser.AccountId).ToArray<Product>();
                    }
                    else
                    {
                        products = dbProduct.GetList(categoryId, 0, 0, eStoreUser.AccountId, "").ToArray<Product>();
                    }
                    int resimSayisi = 0;
                    int hataliResimSayisi = 0;
                    foreach (Product product in products)
                    {
                        IList<ProductImage> ProductImages = dbProduct.GetImageList(product.ProductId);
                        foreach (ProductImage productImage in ProductImages)
                        {
                            try
                            {
                                DownloadImage(productImage.ProductId, Parameters.WebSiteImageUrl + "/product-big/" + productImage.ProductId.ToString() + "_" + productImage.ImageId.ToString() + ".jpg", productImage.ImageId);
                                Logger.Write("Image Resized : " + productImage.ProductId.ToString() + "_" + productImage.ImageId.ToString() + ".jpg", "Trace");
                                resimSayisi++;
                            }
                            catch (Exception ex)
                            {
                                Logger.Write(ex, "Exception");
                                hataliResimSayisi++;
                            }
                        }
                    }
                    return Content(products.Count().ToString() + " Urune ait " + resimSayisi + " Resim Yeniden Boyutlandi. " + hataliResimSayisi + " Resim Hatali.");
                }
                else
                {
                    return Content("Parametreleri Kontrol Ediniz.");
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region Upload Image

        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase file, int Id, string Password, string ImageType, int ImageNo, string FileName)
        {
            Logger.Write("Upload Image -> Pass:" + Password + ",Id:" + Id.ToString() + ",ImageType:" + ImageType + ",ImageNo:" + ImageNo.ToString() + ",FileName:" + FileName + ",File Size:" + file.ContentLength.ToString(), "Trace");
            if (file.ContentLength > 0 && Id > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
            {
                Password = Password.Replace("\r\n", "");
                FileName = FileName.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    Logger.Write("Upload Image -> Password Match", "Trace");

                    Image img = Image.FromStream(file.InputStream, true, true);
                    string ReturnMessage = SaveImage(img, Id, ImageType, ImageNo, FileName);
                    return Content(ReturnMessage);
                }
                else
                {
                    Logger.Write("Upload Image -> Password NOT Match", "Trace");
                    return Content("Sifreyi Kontrol Ediniz.");
                }
            }
            else
            {
                Logger.Write("Upload Image -> Check Parameters", "Trace");
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        public ActionResult ShowImage(int id, int imageId)
        {
            ViewBag.id = id;
            ViewBag.imageId = imageId;
            return View();
        }

        public ActionResult ShowImageGet(ShowImageGetModel sgm)
        {
            sgm.password = dbRefs.GetRef1Old(1911);
            return View(sgm);
        }

        public ActionResult UploadMultipleProductImages(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        public ActionResult UploadMultipleProductImagesGet(ShowImageGetModel sgm)
        {
            sgm.password = dbRefs.GetRef1Old(1911);
            return View(sgm);
        }

        #region single upload custom
        public ActionResult UploadImage2(HttpPostedFileBase file, int Id, string Password, string ImageType, int ImageNo, string FileName)
        {
            var RMessage = "";
            if (file != null && file.ContentLength > 0 && Id > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
            {
                Logger.Write("Upload Image -> Pass:" + Password + ",Id:" + Id.ToString() + ",ImageType:" + ImageType + ",ImageNo:" + ImageNo.ToString() + ",FileName:" + FileName + ",File Size:" + file.ContentLength.ToString(), "Trace");
                Password = Password.Replace("\r\n", "");
                FileName = FileName.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    Logger.Write("Upload Image -> Password Match", "Trace");

                    Image img = Image.FromStream(file.InputStream, true, true);
                    string ReturnMessage = SaveImage(img, Id, ImageType, ImageNo, FileName);
                    RMessage = ReturnMessage;
                }
                else
                {
                    Logger.Write("Upload Image -> Password NOT Match", "Trace");
                    RMessage = "Sifreyi Kontrol Ediniz.";
                }
            }
            else
            {
                Logger.Write("Upload Image -> Check Parameters", "Trace");
                RMessage = "Parametreleri Kontrol Ediniz.";
            }
            if (RMessage == "Resim Kaydedildi.")
            {
                dbProduct.InsertImage(Id, (short)ImageNo);
            }
            var sgm = new ShowImageGetModel();
            sgm.id = Id;
            sgm.imageId = ImageNo;
            sgm.message = string.IsNullOrEmpty(RMessage) ? "" : RMessage;
            sgm.password = dbRefs.GetRef1Old(1911);
            return View("ShowImageGet", sgm);
        }
        #endregion

        #region multi upload custom

        public ActionResult UploadImageMulti(IEnumerable<HttpPostedFileBase> files, int Id, string Password, string ImageType, string FileName)
        {
            int basarisiz = 0;
            int basarili = 0;
            var RMessage = "";
            int ImageNo = 1;
            foreach (var file in files)
            {
                RMessage = "";
                if (file != null && file.ContentLength > 0 && Id > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
                {
                    Logger.Write("Upload Image -> Pass:" + Password + ",Id:" + Id.ToString() + ",ImageType:" + ImageType + ",ImageNo:" + ImageNo.ToString() + ",FileName:" + FileName + ",File Size:" + file.ContentLength.ToString(), "Trace");
                    Password = Password.Replace("\r\n", "");
                    FileName = FileName.Replace("\r\n", "");
                    if (Password == dbRefs.GetRef1Old(1911))
                    {
                        Logger.Write("Upload Image -> Password Match", "Trace");

                        Image img = Image.FromStream(file.InputStream, true, true);
                        string ReturnMessage = SaveImage(img, Id, ImageType, ImageNo, FileName);
                        RMessage = ReturnMessage;
                    }
                    else
                    {
                        Logger.Write("Upload Image -> Password NOT Match", "Trace");
                        RMessage = "Sifreyi Kontrol Ediniz.";
                    }
                }
                if (RMessage == "Resim Kaydedildi.")
                {
                    basarili++;
                    dbProduct.InsertImage(Id, (short)ImageNo);
                }
                else
                {
                    basarisiz++;
                }
                if (ImageNo >= 5)
                {
                    break;
                }
                ImageNo++;
            }
            var sgm = new ShowImageGetModel();
            sgm.id = Id;
            sgm.imageId = 1;
            sgm.message = string.IsNullOrEmpty(RMessage) ? "RefreshIt" : RMessage;
            sgm.password = dbRefs.GetRef1Old(1911);
            return View("UploadMultipleProductImagesGet", sgm);
        }

        #endregion

        #region category image upload custom
        public ActionResult RPImageUpload(HttpPostedFileBase file, int Id, string Password, string ImageType, int ImageNo, string FileName)
        {
            var RMessage = "";
            if (file != null && file.ContentLength > 0 && Id > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
            {
                Logger.Write("Upload Image -> Pass:" + Password + ",Id:" + Id.ToString() + ",ImageType:" + ImageType + ",ImageNo:" + ImageNo.ToString() + ",FileName:" + FileName + ",File Size:" + file.ContentLength.ToString(), "Trace");
                Password = Password.Replace("\r\n", "");
                FileName = FileName.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    Logger.Write("Upload Image -> Password Match", "Trace");

                    Image img = Image.FromStream(file.InputStream, true, true);
                    string ReturnMessage = SaveImage(img, Id, ImageType, ImageNo, FileName);
                    if (ReturnMessage == "Resim Kaydedildi.")
                    {
                        RMessage = "success";
                    }
                    else
                    {
                        RMessage = "error";
                    }
                }
                else
                {
                    Logger.Write("Upload Image -> Password NOT Match", "Trace");
                    RMessage = "error";
                }
            }
            else
            {
                Logger.Write("Upload Image -> Check Parameters", "Trace");
                RMessage = "error";
            }
            if (RMessage == "success" && ImageType == "category-banner")
            {
                int result = dbCategory.SetBannerActive(Id);
                if (result <= 0)
                {
                    RMessage = "error";
                }
            }
            return Content("{'status':'" + RMessage + "'}");
        }
        #endregion

        #endregion

        #region Delete Product Image

        [HttpPost]
        public ActionResult DeleteProductImage(int productId, string Password, string ImageType, int ImageNo)
        {
            var RMessage = "";
            if (productId > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
            {
                try
                {
                    Password = Password.Replace("\r\n", "");
                    if (Password == dbRefs.GetRef1Old(1911))
                    {
                        ImageType = ImageType.Replace("/", "-").ToLower();

                        if (ImageNo == 0) ImageNo = 1;
                        var path = Server.MapPath("~/Images/" + ImageType);

                        if (ImageType == "product")
                        {
                            System.IO.File.Delete(Path.Combine(path + "-big", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-large", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-medium", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-small", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                            {
                                DeleteStorage(ImageType + "-big", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-large", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-medium", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-small", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                            }
                            dbProduct.DeleteImage(productId, (short)ImageNo);
                            RMessage = "Resim Silindi.";
                        }
                        else if (ImageType.StartsWith("category") || ImageType == "pos" || ImageType == "cargo" || ImageType == "banner" || ImageType == "banner-thumb")
                        {
                            System.IO.File.Delete(Path.Combine(path, productId.ToString() + ".jpg"));
                            if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                            {
                                DeleteStorage(ImageType, productId.ToString() + ".jpg");
                            }
                            RMessage = "Resim Silindi.";
                        }
                        else
                        {
                            RMessage = "Bilinmeyen ImageType.";
                        }
                    }
                    else
                    {
                        RMessage = "Parametreleri Kontrol Ediniz.";
                    }
                }
                catch (Exception ex)
                {
                    RMessage = "Hata - " + ex.Message;
                }
            }
            else
            {
                RMessage = "Parametreleri Kontrol Ediniz.";
            }
            var sgm = new ShowImageGetModel();
            sgm.id = productId;
            sgm.imageId = ImageNo;
            sgm.message = string.IsNullOrEmpty(RMessage) ? "" : RMessage;
            sgm.password = dbRefs.GetRef1Old(1911);
            return View("ShowImageGet", sgm);
        }

        #endregion

        #region Delete Product Image Without View

        [HttpPost]
        public ActionResult DeleteProductImage2(int productId, string Password, string ImageType, int ImageNo)
        {
            var RMessage = "";
            if (productId > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
            {
                try
                {
                    Password = Password.Replace("\r\n", "");
                    if (Password == dbRefs.GetRef1Old(1911))
                    {
                        ImageType = ImageType.Replace("/", "-").ToLower();

                        if (ImageNo == 0) ImageNo = 1;
                        var path = Server.MapPath("~/Images/" + ImageType);

                        if (ImageType == "product")
                        {
                            System.IO.File.Delete(Path.Combine(path + "-big", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-large", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-medium", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-small", productId.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                            {
                                DeleteStorage(ImageType + "-big", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-large", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-medium", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-small", productId.ToString() + "_" + ImageNo.ToString() + ".jpg");
                            }
                            dbProduct.DeleteImage(productId, (short)ImageNo);
                            RMessage = "Resim Silindi.";
                        }
                        else if (ImageType.StartsWith("category") || ImageType == "pos" || ImageType == "cargo" || ImageType == "banner" || ImageType == "banner-thumb")
                        {
                            System.IO.File.Delete(Path.Combine(path, productId.ToString() + ".jpg"));
                            if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                            {
                                DeleteStorage(ImageType, productId.ToString() + ".jpg");
                            }
                            RMessage = "Resim Silindi.";
                        }
                        else
                        {
                            RMessage = "Bilinmeyen ImageType.";
                        }
                    }
                    else
                    {
                        RMessage = "Parametreleri Kontrol Ediniz.";
                    }
                }
                catch (Exception ex)
                {
                    RMessage = "Hata - " + ex.Message;
                }
            }
            else
            {
                RMessage = "Parametreleri Kontrol Ediniz.";
            }
            return Content(RMessage);
        }

        #endregion

        #region SaveImage

        private string SaveImage(Image img, int Id, string ImageType, int ImageNo, string FileName, int rotateImage = 0, bool onlyRotateWides = true, bool cropAll = false)
        {
            try
            {
                if (rotateImage != 0)
                {
                    if (rotateImage == 90)
                    {
                        if (onlyRotateWides)
                        {
                            if (img.Width > img.Height)
                            {
                                img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            }
                        }
                        else
                        {
                            img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        }
                    }
                    else if (rotateImage == 180)
                    {
                        if (onlyRotateWides)
                        {
                            if (img.Width > img.Height)
                            {
                                img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            }
                        }
                        else
                        {
                            img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        }
                    }
                    else if (rotateImage == 270)
                    {
                        if (onlyRotateWides)
                        {
                            if (img.Width > img.Height)
                            {
                                img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            }
                        }
                        else
                        {
                            img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        }
                    }
                }

                bool nCrop = false;
                bool wCrop = true;
                bool tCrop = true;
                bool sCrop = true;
                if (cropAll)
                {
                    nCrop = true;
                }


                ImageType = ImageType.Replace("/", "-").ToLower();
                var path = HttpContext.Server.MapPath("/Images/" + ImageType);
                //var path = Path.Combine(HttpRuntime.AppDomainAppPath, "/Images/" + ImageType);


                if (path == null) path = "";

                Logger.Write("Upload Image Path -> Id:" + Id.ToString() + ",ImageType:" + ImageType + ",ImageNo:" + ImageNo.ToString() + ",FileName:" + FileName + ",Path:" + path ?? "", "Trace");

                EncoderParameters encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

                if (ImageType == "product")
                {
                    #region product

                    #region BigResize
                    if (Parameters.ProductWidthBig != 0 || Parameters.ProductHeightBig != 0)
                        resizeImage(img, new Size(Parameters.ProductWidthBig, Parameters.ProductHeightBig), nCrop).Save(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductWideWidthBig != 0 || Parameters.ProductWideHeightBig != 0)
                        resizeImage(img, new Size(Parameters.ProductWideWidthBig, Parameters.ProductWideHeightBig), wCrop).Save(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductTallWidthBig != 0 || Parameters.ProductTallHeightBig != 0)
                        resizeImage(img, new Size(Parameters.ProductTallWidthBig, Parameters.ProductTallHeightBig), tCrop).Save(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductSquareSizeBig != 0)
                        resizeImage(img, new Size(Parameters.ProductSquareSizeBig, Parameters.ProductSquareSizeBig), sCrop).Save(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    #endregion

                    #region LargeResize
                    if (Parameters.ProductWidthLarge != 0 || Parameters.ProductHeightLarge != 0)
                        resizeImage(img, new Size(Parameters.ProductWidthLarge, Parameters.ProductHeightLarge), nCrop).Save(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductWideWidthLarge != 0 || Parameters.ProductWideHeightLarge != 0)
                        resizeImage(img, new Size(Parameters.ProductWideWidthLarge, Parameters.ProductWideHeightLarge), wCrop).Save(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductTallWidthLarge != 0 || Parameters.ProductTallHeightLarge != 0)
                        resizeImage(img, new Size(Parameters.ProductTallWidthLarge, Parameters.ProductTallHeightLarge), tCrop).Save(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductSquareSizeLarge != 0)
                        resizeImage(img, new Size(Parameters.ProductSquareSizeLarge, Parameters.ProductSquareSizeLarge), sCrop).Save(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    #endregion

                    #region MiddleResize
                    if (Parameters.ProductWidthMiddle != 0 || Parameters.ProductHeightMiddle != 0)
                        resizeImage(img, new Size(Parameters.ProductWidthMiddle, Parameters.ProductHeightMiddle), nCrop).Save(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductWideWidthMiddle != 0 || Parameters.ProductWideHeightMiddle != 0)
                        resizeImage(img, new Size(Parameters.ProductWideWidthMiddle, Parameters.ProductWideHeightMiddle), wCrop).Save(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductTallWidthMiddle != 0 || Parameters.ProductTallHeightMiddle != 0)
                        resizeImage(img, new Size(Parameters.ProductTallWidthMiddle, Parameters.ProductTallHeightMiddle), tCrop).Save(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductSquareSizeMiddle != 0)
                        resizeImage(img, new Size(Parameters.ProductSquareSizeMiddle, Parameters.ProductSquareSizeMiddle), sCrop).Save(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    #endregion

                    #region SmallResize
                    if (Parameters.ProductWidthSmall != 0 || Parameters.ProductHeightSmall != 0)
                        resizeImage(img, new Size(Parameters.ProductWidthSmall, Parameters.ProductHeightSmall), nCrop).Save(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductWideWidthSmall != 0 || Parameters.ProductWideHeightSmall != 0)
                        resizeImage(img, new Size(Parameters.ProductWideWidthSmall, Parameters.ProductWideHeightSmall), wCrop).Save(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductTallWidthSmall != 0 || Parameters.ProductTallHeightSmall != 0)
                        resizeImage(img, new Size(Parameters.ProductTallWidthSmall, Parameters.ProductTallHeightSmall), tCrop).Save(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (Parameters.ProductSquareSizeSmall != 0)
                        resizeImage(img, new Size(Parameters.ProductSquareSizeSmall, Parameters.ProductSquareSizeSmall), sCrop).Save(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    #endregion

                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        #region BigUploadStorage
                        UpdateStorage(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), "product-big", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                        if (Parameters.ProductWideWidthBig != 0 || Parameters.ProductWideHeightBig != 0)
                            UpdateStorage(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), "product-big", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg");
                        if (Parameters.ProductTallWidthBig != 0 || Parameters.ProductTallHeightBig != 0)
                            UpdateStorage(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), "product-big", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg");
                        if (Parameters.ProductSquareSizeBig != 0)
                            UpdateStorage(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), "product-big", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg");
                        #endregion

                        #region LargeUploadStorage
                        UpdateStorage(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), "product-large", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                        if (Parameters.ProductWideWidthLarge != 0 || Parameters.ProductWideHeightLarge != 0)
                            UpdateStorage(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), "product-large", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg");
                        if (Parameters.ProductTallWidthLarge != 0 || Parameters.ProductTallHeightLarge != 0)
                            UpdateStorage(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), "product-large", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg");
                        if (Parameters.ProductSquareSizeLarge != 0)
                            UpdateStorage(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), "product-large", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg");
                        #endregion

                        #region MiddleUploadStorage
                        UpdateStorage(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), "product-medium", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                        if (Parameters.ProductWideWidthMiddle != 0 || Parameters.ProductWideHeightMiddle != 0)
                            UpdateStorage(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), "product-medium", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg");
                        if (Parameters.ProductTallWidthMiddle != 0 || Parameters.ProductTallHeightMiddle != 0)
                            UpdateStorage(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), "product-medium", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg");
                        if (Parameters.ProductSquareSizeMiddle != 0)
                            UpdateStorage(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), "product-medium", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg");
                        #endregion

                        #region SmallUploadStorage
                        UpdateStorage(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"), "product-small", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                        if (Parameters.ProductWideWidthSmall != 0 || Parameters.ProductWideHeightSmall != 0)
                            UpdateStorage(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"), "product-small", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg");
                        if (Parameters.ProductTallWidthSmall != 0 || Parameters.ProductTallHeightSmall != 0)
                            UpdateStorage(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"), "product-small", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg");
                        if (Parameters.ProductSquareSizeSmall != 0)
                            UpdateStorage(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"), "product-small", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg");
                        #endregion

                        #region BigDelete
                        System.IO.File.Delete(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                        if (Parameters.ProductWideWidthBig != 0 || Parameters.ProductWideHeightBig != 0)
                            System.IO.File.Delete(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"));
                        if (Parameters.ProductTallWidthBig != 0 || Parameters.ProductTallHeightBig != 0)
                            System.IO.File.Delete(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"));
                        if (Parameters.ProductSquareSizeBig != 0)
                            System.IO.File.Delete(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"));
                        #endregion

                        #region LargeDelete
                        System.IO.File.Delete(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                        if (Parameters.ProductWideWidthLarge != 0 || Parameters.ProductWideHeightLarge != 0)
                            System.IO.File.Delete(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"));
                        if (Parameters.ProductTallWidthLarge != 0 || Parameters.ProductTallHeightLarge != 0)
                            System.IO.File.Delete(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"));
                        if (Parameters.ProductSquareSizeLarge != 0)
                            System.IO.File.Delete(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"));

                        #endregion

                        #region MiddleDelete
                        System.IO.File.Delete(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                        if (Parameters.ProductWideWidthMiddle != 0 || Parameters.ProductWideHeightMiddle != 0)
                            System.IO.File.Delete(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"));
                        if (Parameters.ProductTallWidthMiddle != 0 || Parameters.ProductTallHeightMiddle != 0)
                            System.IO.File.Delete(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"));
                        if (Parameters.ProductSquareSizeMiddle != 0)
                            System.IO.File.Delete(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"));
                        #endregion

                        #region SmallDelete
                        System.IO.File.Delete(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                        if (Parameters.ProductWideWidthSmall != 0 || Parameters.ProductWideHeightSmall != 0)
                            System.IO.File.Delete(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_w.jpg"));
                        if (Parameters.ProductTallWidthSmall != 0 || Parameters.ProductTallHeightSmall != 0)
                            System.IO.File.Delete(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_t.jpg"));
                        if (Parameters.ProductSquareSizeSmall != 0)
                            System.IO.File.Delete(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + "_s.jpg"));
                        #endregion
                    }

                    #endregion
                }
                else if (ImageType == "category-banner")
                {
                    #region category-banner

                    resizeImage(img, new Size((int)dbRefs.GetRef3Old(1920), (int)dbRefs.GetRef3Old(1921))).Save(Path.Combine(path, Id.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, Id.ToString() + ".jpg"), ImageType, Id.ToString() + ".jpg");
                    }

                    #endregion
                }
                else if (ImageType == "category")
                {
                    #region category

                    resizeImage(img, new Size((int)dbRefs.GetRef3Old(1922), (int)dbRefs.GetRef3Old(1923))).Save(Path.Combine(path, Id.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, Id.ToString() + ".jpg"), ImageType, Id.ToString() + ".jpg");
                    }

                    #endregion
                }
                else if (ImageType == "cargo")
                {
                    #region cargo

                    resizeImage(img, new Size((int)dbRefs.GetRef3Old(1924), (int)dbRefs.GetRef3Old(1925))).Save(Path.Combine(path, Id.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, Id.ToString() + ".jpg"), ImageType, Id.ToString() + ".jpg");
                    }

                    #endregion
                }
                else if (ImageType == "pos")
                {
                    #region pos

                    resizeImage(img, new Size((int)dbRefs.GetRef3Old(1926), (int)dbRefs.GetRef3Old(1927))).Save(Path.Combine(path, Id.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, Id.ToString() + ".jpg"), ImageType, Id.ToString() + ".jpg");
                    }

                    #endregion
                }
                else if (ImageType == "upload")
                {
                    #region upload

                    //img.Save(Path.Combine(path, FileName), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    Logger.Write("Path To Save Image : " + Path.Combine(path, FileName), "Trace");
                    img.Save(Path.Combine(path, FileName));
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, FileName), ImageType, FileName);
                    }

                    #endregion
                }
                else if (ImageType == "banner")
                {
                    #region banner

                    IList<Banner> BannerList = dbBanner.GetAll();
                    string BannerType = BannerList.Where(o => o.BannerID == Id).FirstOrDefault().Name;

                    resizeImage(img, new Size((int)dbRefs.GetRef3Old(1928), (int)dbRefs.GetRef3Old(1929)), true).Save(Path.Combine(path, Id.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, Id.ToString() + ".jpg"), ImageType, Id.ToString() + ".jpg");
                    }

                    #endregion
                }
                else if (ImageType == "banner-thumb")
                {
                    #region banner-thumb

                    resizeImage(img, new Size((int)dbRefs.GetRef3Old(1930), (int)dbRefs.GetRef3Old(1931)), true).Save(Path.Combine(path, Id.ToString() + ".jpg"), GetEncoder(ImageFormat.Jpeg), encoderParameters);
                    if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                    {
                        UpdateStorage(Path.Combine(path, Id.ToString() + ".jpg"), ImageType, Id.ToString() + ".jpg");
                    }

                    #endregion
                }
                else
                {
                    return "Bilinmeyen ImageType.";
                }
                return "Resim Kaydedildi.";
            }
            catch (Exception ex)
            {
                Logger.Write(ex, "Exception");
                return ex.Message.ToString();
            }
        }

        #endregion

        #region Delete Image

        [HttpPost]
        public ActionResult DeleteImage(int Id, string Password, string ImageType, int ImageNo)
        {
            if (Id > 0 && Password != null && Password != "" && ImageType != null && ImageType != "")
            {
                try
                {
                    Password = Password.Replace("\r\n", "");
                    if (Password == dbRefs.GetRef1Old(1911))
                    {
                        ImageType = ImageType.Replace("/", "-").ToLower();

                        if (ImageNo == 0) ImageNo = 1;
                        var path = Server.MapPath("~/Images/" + ImageType);

                        if (ImageType == "product")
                        {
                            System.IO.File.Delete(Path.Combine(path + "-big", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-large", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-medium", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            System.IO.File.Delete(Path.Combine(path + "-small", Id.ToString() + "_" + ImageNo.ToString() + ".jpg"));
                            if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                            {
                                DeleteStorage(ImageType + "-big", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-large", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-medium", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                                DeleteStorage(ImageType + "-small", Id.ToString() + "_" + ImageNo.ToString() + ".jpg");
                            }
                            dbProduct.DeleteImage(Id, (short)ImageNo);
                        }
                        else if (ImageType.StartsWith("category") || ImageType == "pos" || ImageType == "cargo" || ImageType == "banner" || ImageType == "banner-thumb")
                        {
                            System.IO.File.Delete(Path.Combine(path, Id.ToString() + ".jpg"));
                            if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                            {
                                DeleteStorage(ImageType, Id.ToString() + ".jpg");
                            }
                        }
                        else
                        {
                            return Content("Bilinmeyen ImageType.");
                        }
                        return Content("Resim Silindi.");
                    }
                    else
                    {
                        return Content("Parametreleri Kontrol Ediniz.");
                    }
                }
                catch (Exception ex)
                {
                    return Content("Hata - " + ex.Message);
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region resizeImage

        private static Image resizeImage(Image imgToResize, Size size, Boolean crop = false)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;
            var cropImage = crop;
            int destWidth = 0;
            int destHeight = 0;
            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            int xPos = 0;
            int yPos = 0;

            if (cropImage)
            {
                #region crop
                nPercentW = ((float)size.Width / (float)sourceWidth);
                nPercentH = ((float)size.Height / (float)sourceHeight);

                //new
                if (nPercentH > nPercentW)
                    nPercent = nPercentH;
                else
                    nPercent = nPercentW;

                destWidth = (int)(sourceWidth * nPercent);
                destHeight = (int)(sourceHeight * nPercent);

                Bitmap newImage = null;
                newImage = new Bitmap(size.Width, size.Height);

                int startX = 0;
                int startY = 0;

                if (destWidth > size.Width)
                    startX = 0 - ((destWidth - size.Width) / 2);

                if (destHeight > size.Height)
                    startY = 0 - ((destHeight - size.Height) / 2);

                using (Graphics graphics = Graphics.FromImage((System.Drawing.Image)newImage))
                {
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.DrawImage(imgToResize, startX, startY, destWidth, destHeight);
                }
                return (System.Drawing.Image)newImage;


                #endregion
            }
            else
            {
                #region dontCrop

                nPercentW = ((float)size.Width / (float)sourceWidth);
                nPercentH = ((float)size.Height / (float)sourceHeight);

                if (nPercentH < nPercentW)
                    nPercent = nPercentH;
                else
                    nPercent = nPercentW;

                destWidth = (int)(sourceWidth * nPercent);
                destHeight = (int)(sourceHeight * nPercent);

                //resmi oluştur
                Bitmap b = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage((Image)b);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(imgToResize, xPos, yPos, destWidth, destHeight);
                g.Dispose();
                return (Image)b;

                #endregion
            }
        }

        #endregion

        #region GetEncoder

        //public static void SaveJPG100(this Bitmap bmp, string filename)
        //{
        //    EncoderParameters encoderParameters = new EncoderParameters(1);
        //    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        //    bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
        //}

        //public static void SaveJPG100(this Bitmap bmp, Stream stream)
        //{
        //    EncoderParameters encoderParameters = new EncoderParameters(1);
        //    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        //    bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
        //}

        public static ImageCodecInfo GetEncoder(ImageFormat format)
        {

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

        #endregion

        #region UpdateStorage

        private void UpdateStorage(string Path, string ImageType, string ImageName)
        {
            try
            {
                if (!string.IsNullOrEmpty(Parameters.StorageAccount))
                {
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Parameters.StorageConnectionString);

                    // Create the blob client.
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    blobClient.RetryPolicy = RetryPolicies.Retry(4, TimeSpan.Zero);

                    // Retrieve reference to a previously created container.
                    CloudBlobContainer container = blobClient.GetContainerReference(ImageType);
                    container.CreateIfNotExist();
                    container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

                    // Retrieve reference to a blob named "myblob".
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageName);
                    blockBlob.Properties.ContentType = "image\\jpeg";
                    blockBlob.Properties.CacheControl = "public, max-age=86400";

                    //CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageName);

                    // Create or overwrite the "myblob" blob with contents from a local file.
                    using (var fileStream = System.IO.File.OpenRead(Path))
                    {
                        blockBlob.UploadFromStream(fileStream);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write("Path = " + Path + " , FileName = " + ImageName + " -> " + ex.Message, "Exception");
            }
        }

        #endregion

        #region DeleteStorage

        private void DeleteStorage(string ImageType, string ImageName)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Parameters.StorageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            blobClient.RetryPolicy = RetryPolicies.Retry(4, TimeSpan.Zero);

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(ImageType);
            container.CreateIfNotExist();
            container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageName);

            blockBlob.DeleteIfExists();
        }

        #endregion

        #region Export XML

        [HttpGet]
        public ActionResult ExportXML(short XmlId, int Id, string Password)
        {
            if (XmlId > 0 && Id > 0 && Password != null && Password != "")
            {
                string apikey = dbRefs.GetRef1Old(2125);
                string secretkey = dbRefs.GetRef1Old(2126);
                string rolename = dbRefs.GetRef1Old(2128);
                string rolepass = dbRefs.GetRef1Old(2129);
                var websiteUrl = dbRefs.GetRef1(1913) == "E" ? Parameters.WebSiteUrl.Replace("http://", "https://") : Parameters.WebSiteUrl;

                AuthConfig config = new AuthConfig();
                config.ApiKey = apikey;
                config.SecretKey = secretkey;
                config.RoleName = rolename;
                config.RolePass = rolepass;
                ConfigurationManager.setAuthParameters(config);

                ConfigurationManager.getAuthParameters();
                ProductService ProductServices = ServiceProvider.getProductService();

                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    try
                    {

                        if (XmlId == int.Parse(dbRefs.GetRef1Old(2127)))
                        {
                            #region Category Çekme Kodları
                            //gittigidiyor entegrasyon
                            //AuhtService.CommunityAuthServiceClient token = new AuhtService.CommunityAuthServiceClient();


                            //CategoryService categoryservice = ServiceProvider.getCategoryService();
                            //StringBuilder t = new StringBuilder();
                            ////categoryServiceResponse eeee = categoryservice.getCategory("sgf", true, true, true, "tr");
                            //for (int i = 0; i < 3900; i++)
                            //{
                            //    categoryServiceResponse eeese = categoryservice.getCategories(i, 100, true, true, true, "tr");
                            //    foreach (var item in eeese.categories)
                            //    {
                            //        t.AppendLine(item.categoryCode + "&" + item.categoryName + "<br/>");
                            //    }
                            //    i = i + 99;

                            //} 
                            #endregion

                            IList<Product> ProductList = dbXml.GetProductList(XmlId);

                            foreach (Product item in ProductList)
                            {
                                productType exportproduct = new productType();
                                exportproduct.title = item.ProductName;
                                exportproduct.subtitle = item.GGSubTitle;
                                exportproduct.boldOption = item.GGBoldOption;
                                exportproduct.description = item.Description.Replace("\r\n", "<br>") + dbProductInfo.GetListHtml(item.ProductId);
                                exportproduct.categoryCode = item.GGCategoryCode;
                                exportproduct.format = "A";

                                photoType photo = new photoType();
                                photo.photoId = 0;
                                photo.photoIdSpecified = true;
                                photo.url = Parameters.WebSiteImageUrl + "/product-big/" + item.ProductId + ".jpg";

                                photoType[] photoarray = new photoType[1];
                                photoarray[0] = photo;

                                exportproduct.photos = photoarray;
                                List<ProductInfo> productinfos = dbProductInfo.GetList(item.ProductId).ToList();

                                List<specType> speclist = new List<specType>();
                                foreach (ProductInfo info in productinfos)
                                {
                                    specType spec = new specType();
                                    spec.name = info.Type;
                                    spec.value = info.Information;
                                    speclist.Add(spec);
                                }
                                exportproduct.specs = speclist.ToArray();

                                exportproduct.pageTemplate = 1;
                                exportproduct.pageTemplateSpecified = true;

                                exportproduct.buyNowPrice = double.Parse(item.PriceWithTax.ToString()) * 1.10;
                                exportproduct.buyNowPriceSpecified = true;

                                exportproduct.startPrice = 1;
                                exportproduct.startPriceSpecified = false;

                                exportproduct.listingDays = 30;
                                exportproduct.listingDaysSpecified = true;

                                exportproduct.productCount = 1;
                                exportproduct.productCountSpecified = true;

                                cargoDetailType cargo = new cargoDetailType();
                                cargo.city = "34";
                                string[] cargocampany = new string[3];
                                cargocampany[0] = "aras";

                                cargo.cargoCompanies = cargocampany;

                                cargo.cargoDescription = item.FastCargo ? "15:00'a kadar verilen siparişler aynı gün teslim edilir" : "Ertesi gün teslim edilir";

                                if (item.FreeCargo)
                                {
                                    cargo.shippingPayment = "S";
                                }
                                else
                                {
                                    cargo.shippingPayment = "B";
                                }

                                cargo.shippingWhere = "country";

                                exportproduct.cargoDetail = cargo;
                                exportproduct.startDate = Parameters.Now.ToString("yyyy-MM-dd HH:mm:ss");

                                productServiceResponse result = ProductServices.insertProduct(item.ProductId.ToString(), exportproduct, true, false, "tr");

                                //  ProductServices.updateProduct(item.GGProductId, item.ProductId, exportproduct, true, false, false, "tr");

                                if (result != null && result.ackCode.ToString().Equals("sucess"))
                                {
                                    dbProduct.UpdateGGProductId(item.ProductId, result.productId);
                                    return Content("OK");

                                }
                                else
                                {
                                    return Content(result.error.errorCode + " - " + result.error.message);
                                }
                            }

                        }

                        return Content("OK");
                    }
                    catch (Exception ex)
                    {
                        return Content(ex.Message);

                    }

                }
                else
                {

                    return Content("Parametreleri Kontrol Ediniz.");
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region Import XML

        #region ImportXML

        [HttpPost]
        public ActionResult ImportXML(short XmlId, string Password)
        {
            if (XmlId > 0 && Password != null && Password != "")
            {
                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    XmlImport xml = dbXmlImport.Get(XmlId);
                    IList<XmlImport> xmlList = dbXmlImport.GetListById(XmlId);
                    //string returnMessage = BindData(xml);
                    Thread thread = new Thread(() => BindData(xml, xmlList));
                    thread.Start();
                    return Content("XML Import Baslatiliyor...");
                }
                else
                {
                    return Content("Parametreleri Kontrol Ediniz.");
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region Semafor

        private static object Semafor = new object();

        #endregion

        #region BindData

        private void BindData(XmlImport xml, IList<XmlImport> xmlList)
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder sbReport = new StringBuilder();

            string ProcessedProductCode = "";
            int newProductCounter = 0;
            int productCounterr = 0;
            string fiyatSifir = "";
            string kategoriSifir = "";
            string markaSifir = "";
            string ekstraSifir = "";
            string ekstraDetaySifir = "";
            try
            {
                lock (Semafor)
                {
                    Uri addr = new Uri(xml.Url);

                    Logger.Write("XML Import File Started To Download : " + xml.Description + " - " + xml.Url, "Trace");

                    bool Success = false;
                    string XMLContent = ConnectRestEC(addr, out Success);

                    if (Success)
                    {
                        Logger.Write("XML Import Started : " + xml.Description, "Trace");

                        #region ExchangeRates

                        IList<ExchangeRate> TCMBExchangeRates = new List<ExchangeRate>();
                        IList<ExchangeRate> ExchangeRates = dbExchangeRate.GetList(Parameters.DefaultExchangeType, DateTime.Today);
                        if (ExchangeRates == null || ExchangeRates.Count == 0)
                        {
                            Logger.Write("XML Import Getting TCMB Exchanged Rates", "Trace");

                            TCMBExchangeRates = TCMBDovizKurAl();
                            IList<Exchange> exchanges = dbExchange.GetList();
                            if (exchanges != null)
                            {
                                foreach (Exchange exchange in exchanges)
                                {
                                    ExchangeRate exchangeRate = TCMBExchangeRates.Where(r => r.ExchangeId == exchange.ExchangeId).FirstOrDefault();
                                    if (exchangeRate != null)
                                    {
                                        dbExchangeRate.Insert(exchangeRate.ExchangeId, exchangeRate.ExchangeName, Parameters.DefaultExchangeType, DateTime.Today, exchangeRate.Rate, "Import");
                                    }
                                }
                            }
                            ExchangeRates = dbExchangeRate.GetList(Parameters.DefaultExchangeType, DateTime.Today);
                        }

                        #endregion

                        XDocument xDoc = XDocument.Parse(XMLContent.Replace("windows-1254", "utf-8"));
                        int ProductCount = 0;

                        if (xml.Description.ToUpperInvariant().Contains("INDEX") || xml.Description.ToUpperInvariant().Contains("NEOPAZAR") || xml.Description.ToUpperInvariant().Contains("HOMEND"))
                        {
                            #region Index-NeoPazar-Homend

                            #region tedarik kurtar
                            //var zz = 1;
                            //if (zz == 1)
                            //{
                            //    Uri addrKat = new Uri("http://www.serhatyilmaz.com.tr/_test/indexkatalog.xml");
                            //    bool KatSuccess = false;
                            //    string KatXMLContent = ConnectRestEC(addrKat, out KatSuccess);
                            //    XDocument xDocKat = XDocument.Parse(KatXMLContent.Replace("windows-1254", "utf-8"));
                            //    List<XElement> UrunList = xDocKat.Descendants("URUN").ToList();


                            //    Uri addrFiy = new Uri("http://www.serhatyilmaz.com.tr/_test/indexfiyat.xml");
                            //    bool FiySuccess = false;
                            //    string FiyXMLContent = ConnectRestEC(addrFiy, out FiySuccess);
                            //    XDocument xDocFiy = XDocument.Parse(FiyXMLContent.Replace("windows-1254", "utf-8"));
                            //    List<XElement> FiyatList = xDocFiy.Descendants("URUN").ToList();

                            //    var olanlar = 0;
                            //    var hicolmayanlar = 0;
                            //    var zatenolanlar = 0;
                            //    var urunsayisi = 0;

                            //    foreach (var urun in UrunList)
                            //    {
                            //        #region tedarik kurtar
                            //        //lazım olanlar: ok KRTID, ok XMLID, ok XMLKARTID, ok XMLKARTKOD, ok XMLKARTBARKOD, ok ALISFIYATI, ok STOKMIKTAR, ok STOKMIKTARYOLDA, ok GUNCELLE
                            //        string PName = urun.Attributes("AD").FirstOrDefault().Value;

                            //        int pId = dbProduct.GetProductIdByProductName(PName);
                            //        if (pId > 0)
                            //        {
                            //            string xpId = urun.Attributes("KOD").FirstOrDefault().Value;
                            //            decimal xBuyingPrice = 0;
                            //            decimal xAmount = xml.Amount;
                            //            decimal xAmountOnRoad = xml.AmountOnRoad;

                            //            int xxProId = dbProduct.insertStokKartSaticiByName(pId, xml.XmlId, xpId, xpId, xpId, xBuyingPrice, xAmount, xAmountOnRoad, 1);
                            //            olanlar++;
                            //            if (olanlar == 425)
                            //            {
                            //                olanlar = olanlar + 0;
                            //            }
                            //        }
                            //        else if (pId == -1)
                            //        {
                            //            hicolmayanlar++;
                            //        }
                            //        else
                            //        {
                            //            zatenolanlar++;
                            //        }
                            //        urunsayisi++;
                            //        if (urunsayisi == UrunList.Count() - 2)
                            //        {
                            //            var z = 1;
                            //        }

                            //        continue;

                            //        #endregion
                            //    }


                            //}
                            //else 

                            #endregion

                            if (xml.Description.ToUpperInvariant().Contains("KATALOG"))
                            {

                                #region Index Katalog Xml

                                #region Sample XML

                                //<INDEXGRUP>
                                //  <KATEGORI KOD="IDX1031" TANIM="AĞ (Network) Ürünleri">
                                //    <GRUP KOD="1539" TANIM="Yönlendirici (Router)">
                                //      <URUN KOD="AIR-4420-3G" AD="AIRTIES AIR 4420 300 Mbps 11N 5Ghz 3G Router" MARKA="AIRTIES" GLOBALKOD="AIR-4420/3G" SIRKETKOD="IDX">
                                //        <VERGI>KDV18</VERGI>
                                //        <RESIM>http://www.indexpazar.com/all_images/AIR-44203G.jpg</RESIM>
                                //        <OZELLIK>
                                //          <OZL TANIM="Anten " DEGER="Sabit Anten/dahili" />
                                //          <OZL TANIM="Çalışma Frekansı" DEGER="5 GHz" />
                                //          <OZL TANIM="Garanti" DEGER="3 yıl" />
                                //          <OZL TANIM="Özellikler" DEGER="GSM operatörlerinden her hangi birisinin 3G usb modemini bağlayarak internet bağlantısnı kablosuz paylaşabilirsiniz.Airtouch özelliği var. Sadece Tek tuşa basarak mevcut ağ genişletilebilir." />
                                //          <OZL TANIM="Uygulama Alanı" DEGER="İç Ortam (Indoor)" />
                                //          <OZL TANIM="Ürün Özelliği" DEGER="Router " />
                                //          <OZL TANIM="Veri iletişim Hızı" DEGER="300 Mbps 802.11b/g/n" />
                                //        </OZELLIK>
                                //      </URUN>

                                #endregion

                                List<XElement> categorilist = xDoc.Descendants("INDEXGRUP").Descendants("KATEGORI").ToList();

                                Logger.Write("XML Import Ana Kategori Sayısı : " + categorilist.Count.ToString(), "Trace");

                                foreach (var categori in categorilist)
                                {
                                    #region Processed Product Count Log

                                    ProductCount++;
                                    Logger.Write(ProductCount.ToString() + ". Ana Kategori İşlem Görüyor", "Trace");

                                    #endregion

                                    string categoryname = categori.Attributes("TANIM").FirstOrDefault().Value;

                                    #region Main Category Control

                                    XmlImportGroup xmlImportGroup = dbXmlImport.GetGroup(xml.XmlIdForProductId, categoryname);
                                    if (xmlImportGroup == null)
                                    {
                                        int anaKategoriId = dbCategory.GetByName(categoryname);
                                        if (anaKategoriId > 0)
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, categoryname, anaKategoriId, false);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, categoryname, 0, false);
                                        }
                                        xmlImportGroup = dbXmlImport.GetGroup(xml.XmlId, categoryname);
                                    }
                                    Category category = dbCategory.Get(xmlImportGroup.GroupId);
                                    if (!xmlImportGroup.IsActive || category == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    List<XElement> obj = categori.Descendants("GRUP").ToList();

                                    foreach (XElement item in obj)
                                    {
                                        string groupname = item.Attributes("TANIM").FirstOrDefault().Value;

                                        #region Category Control

                                        XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname);
                                        if (xmlImportGroup2 == null)
                                        {
                                            int altGrupId = dbCategory.GetByName(groupname);
                                            if (altGrupId > 0)
                                            {
                                                dbXmlImport.InsertGroup(xml.XmlId, groupname, altGrupId, false);
                                            }
                                            else
                                            {
                                                dbXmlImport.InsertGroup(xml.XmlId, groupname, 0, false);
                                            }
                                            sbReport.Append("Grup Oluşturuldu : " + groupname);
                                            xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname);
                                        }
                                        Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                        if (!xmlImportGroup2.IsActive || category2 == null)
                                        {
                                            continue;
                                        }

                                        #endregion

                                        List<XElement> UrunList = item.Descendants("URUN").ToList();

                                        foreach (var urun in UrunList)
                                        {
                                            string brand = urun.Attributes("MARKA").FirstOrDefault().Value;

                                            #region Brand Control

                                            XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                            if (xmlBrand == null)
                                            {
                                                int brandId = dbCategory.GetByName(brand);
                                                if (brandId > 0)
                                                {
                                                    dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                                    xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                                }
                                                else
                                                {
                                                    dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                                    continue;
                                                }
                                                sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname + ")");
                                            }
                                            Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                            if (!xmlBrand.IsActive || brandGroup == null)
                                            {
                                                continue;
                                            }

                                            #endregion

                                            ProcessedProductCode = urun.Attributes("KOD").FirstOrDefault().Value;
                                            string DealerProductId = ProcessedProductCode;
                                            string ImageUrl = urun.Descendants("RESIM").FirstOrDefault().Value;
                                            string kdv = urun.Descendants("VERGI").FirstOrDefault().Value;
                                            kdv = kdv.Replace("KDV", "");

                                            int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProcessedProductCode);

                                            if (productId == -2)
                                            {
                                                continue;
                                            }

                                            Product _Product = new Product();
                                            _Product.ProductCode = ProcessedProductCode;
                                            if (!xml.StkNameNotUpdate)
                                            {
                                                _Product.ProductName = urun.Attributes("AD").FirstOrDefault().Value;
                                            }
                                            _Product.CategoryId = category2.CategoryId;
                                            _Product.BrandId = brandGroup.CategoryId;
                                            _Product.TaxRate = decimal.Parse(kdv);
                                            _Product.Desi = 0;
                                            _Product.xmlBrandId = xmlBrand.Id;
                                            _Product.xmlGroupId = xmlImportGroup2.Id;
                                            if (xmlImportGroup2.Desi == 0)
                                            {
                                                _Product.Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                            }
                                            else
                                            {
                                                _Product.Desi = xmlImportGroup2.Desi;
                                            }

                                            _Product.DeliveryPeriod = "Gün";
                                            _Product.DeliveryTime = xml.DeliveryTime;

                                            bool NewProduct = false;

                                            if (productId == -1 && xml.InsertNewProduct)
                                            {
                                                productId = dbProduct.Insert(xml.XmlIdForProductId, _Product, xml.ReloadDescription);
                                                NewProduct = true;
                                                newProductCounter++;
                                            }
                                            else
                                            {
                                                if (xml.StkNameNotUpdate)
                                                {
                                                    productId = dbProduct.InsertWithoutName(xml.XmlIdForProductId, _Product, xml.ReloadDescription);
                                                }
                                                else
                                                {
                                                    productId = dbProduct.Insert(xml.XmlIdForProductId, _Product, xml.ReloadDescription);
                                                }
                                            }
                                            if (NewProduct || xml.ReInstallProductImg)
                                            {
                                                #region New Product to Update Image

                                                if (productId > 0 && !string.IsNullOrEmpty(ImageUrl))
                                                {
                                                    try
                                                    {
                                                        DownloadImage(productId, ImageUrl, 1);
                                                    }
                                                    catch
                                                    {
                                                        Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                        sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                                    }
                                                }

                                                #endregion
                                            }
                                            if (productId > 0)
                                            {
                                                #region Stok Kart Ekstra Alanlar

                                                foreach (var productinfo in urun.Descendants("OZELLIK").Descendants("OZL"))
                                                {
                                                    string Information = productinfo.Attributes("DEGER").FirstOrDefault().Value;
                                                    string type = productinfo.Attributes("TANIM").FirstOrDefault().Value;

                                                    dbProductInfo.Insert(productId, type, Information);
                                                }

                                                #endregion

                                                #region Stok Kart Ekstra Gruplar

                                                foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                                {
                                                    dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                                }

                                                #endregion
                                            }
                                        }
                                    }
                                }

                                #endregion
                            }
                            else if (xml.Description.ToUpperInvariant().Contains("FIYAT") || xml.Description.ToUpperInvariant().Contains("FİYAT"))
                            {
                                #region Index Fiyat Xml

                                #region Sample XML

                                //<INDEXGRUP>
                                //  <URUN KOD="WD1500HLFS" OZEL="155,3000" BAYI="158,5000" MUSTERI="188,0000" PB="USD" SIRKET="IDX" />
                                //  <URUN KOD="WD1600AAJS" OZEL="57,7000" BAYI="57,7000" MUSTERI="72,1300" PB="USD" SIRKET="IDX" />
                                //  <URUN KOD="WD1600BEVE" OZEL="103,0000" BAYI="105,2000" MUSTERI="131,5000" PB="USD" SIRKET="IDX" />
                                //  <URUN KOD="WD1600BEVT" OZEL="86,7700" BAYI="86,7700" MUSTERI="104,0000" PB="USD" SIRKET="IDX" />

                                #endregion

                                List<XElement> pricelist = xDoc.Descendants("INDEXGRUP").Descendants("URUN").ToList();

                                Logger.Write("XML Import Kayıt Sayısı : " + pricelist.Count.ToString(), "Trace");

                                foreach (var item in pricelist)
                                {
                                    #region Processed Product Count Log

                                    ProductCount++;
                                    if (ProductCount % 100 == 0)
                                    {
                                        Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                    }

                                    #endregion


                                    ProcessedProductCode = item.Attributes("KOD").FirstOrDefault().Value;
                                    string ProductCode = ProcessedProductCode;
                                    int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductCode);



                                    if (productId == -2)
                                    {
                                        continue;
                                    }
                                    if (productId > 0)
                                    {

                                        #region ProfitRate Control

                                        ProductProfitRate xmlProfitRates = new ProductProfitRate();
                                        xmlProfitRates = dbProduct.GetProfitRateByProductId(productId);
                                        decimal ProductProfitRate;
                                        if (xmlProfitRates.BrandProfitRate != 0)
                                            ProductProfitRate = xmlProfitRates.BrandProfitRate;
                                        else if (xmlProfitRates.GroupProfitRate != 0)
                                            ProductProfitRate = xmlProfitRates.GroupProfitRate;
                                        else
                                            ProductProfitRate = xml.ProfitRate;

                                        #endregion

                                        decimal specialprice = XEAttributeResultDecimal(item, "OZEL", xml.DecimalPoint);
                                        decimal Price = XEAttributeResultDecimal(item, "BAYI", xml.DecimalPoint);
                                        decimal salesprice = XEAttributeResultDecimal(item, "MUSTERI", xml.DecimalPoint);

                                        string doviz = ChangeExchangeCode(item.Attributes("PB").FirstOrDefault().Value);
                                        if (doviz != "TL")
                                        {
                                            decimal rate = GetRate(ExchangeRates, TCMBExchangeRates, doviz);

                                            Price = Math.Round(Price * rate, 2);
                                            salesprice = Math.Round(salesprice * rate, 2);
                                            specialprice = Math.Round(specialprice * rate, 2);
                                            doviz = "TL";
                                        }

                                        decimal BuyingPrice = salesprice;

                                        if (specialprice > 0 && ProductProfitRate > 1)
                                        {
                                            salesprice = specialprice;
                                            BuyingPrice = specialprice;
                                        }

                                        salesprice = Math.Round(salesprice * ProductProfitRate, 2);

                                        if (xml.PriceLimit > 0 && xml.PriceLimit >= salesprice)
                                        {
                                            salesprice += xml.PriceToAdd;
                                        }
                                        if (xml.PriceToAddAll > 0)
                                        {
                                            salesprice += xml.PriceToAddAll;
                                        }


                                        dbProduct.UpdatePrice(xml.XmlIdForProductId, productId, salesprice, BuyingPrice, doviz);
                                    }
                                }

                                #endregion
                            }
                            else if (xml.Description.ToUpperInvariant().Contains("STOK"))
                            {
                                #region Index Stok Xml

                                #region Sample XML

                                //<INDEXGRUP>
                                //  <URUN KOD="GH24NS95" STOK="100+" YOL="0" SIRKET="IDX" />
                                //  <URUN KOD="DTIG3-8GBZ" STOK="100+" YOL="0" SIRKET="IDX" />

                                #endregion

                                List<XElement> stocklist = xDoc.Descendants("INDEXGRUP").Descendants("URUN").ToList();

                                dbProduct.ResetAmount(xml.XmlIdForProductId);

                                Logger.Write("XML Import Kayıt Sayısı : " + stocklist.Count.ToString(), "Trace");

                                foreach (var item in stocklist)
                                {
                                    #region Processed Product Count Log

                                    ProductCount++;
                                    if (ProductCount % 100 == 0)
                                    {
                                        Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                    }

                                    #endregion

                                    ProcessedProductCode = item.Attributes("KOD").FirstOrDefault().Value;
                                    string ProductCode = ProcessedProductCode;
                                    int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductCode);

                                    if (productId == -2)
                                    {
                                        productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProcessedProductCode);
                                    }
                                    if (productId > 0)
                                    {
                                        string stokbakiyeST = item.Attributes("STOK").FirstOrDefault().Value;
                                        string stokyoldaST = item.Attributes("YOL").FirstOrDefault().Value;
                                        int stokbakiye = int.Parse(stokbakiyeST.ToString().Replace("+", ""));
                                        int stokyolda = int.Parse(stokyoldaST.ToString().Replace("+", ""));
                                        bool FastCargo = true;
                                        if (stokbakiye == 0)
                                        {
                                            FastCargo = false;
                                        }

                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, stokbakiye, stokyolda);
                                    }
                                }

                                dbProduct.SetInactive(xml.XmlIdForProductId);

                                #endregion
                            }

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("GAMA") && xml.Description.ToUpperInvariant().Contains("BİLGİSAYAR") || xml.Description.ToUpperInvariant().Contains("BILGISAYAR"))
                        {
                            #region Gama Bilgisayar
                            if (xml.Description.ToUpperInvariant().Contains("KATALOG"))
                            {
                                #region Gama Ürün - Kategori - Marka XML - StokFiyat XML

                                #region GetXMLs

                                string kategoriXmlUrl = "http://bayi.e-gama.com/emails/bayiy/category.xml";
                                string markaXmlUrl = "http://bayi.e-gama.com/emails/bayiy/brand.xml";
                                string fiyatXmlUrl = "http://bayi.e-gama.com/emails/bayiy/stockPrice.xml";
                                string productPropertyXmlUrl = "http://bayi.e-gama.com/emails/bayiy/productProperty.xml";
                                string propertyXmlUrl = "http://bayi.e-gama.com/emails/bayiy/property.xml";
                                //double sepFinder = 1 / 2;
                                //string seperator = Math.Round(sepFinder, 2).ToString();
                                //seperator = seperator.Substring(1, 1);

                                //Kategori Xml Get
                                #region Kategori Sample XML
                                //<categories>
                                //  <category>
                                //    <active>1</active>
                                //    <categoryCode>1</categoryCode>
                                //    <parentCategoryCode>0</parentCategoryCode>
                                //    <translations>
                                //      <translation>
                                //        <desc/>
                                //        <languageCode>TUR</languageCode>
                                //        <name>Baskı Çözümleri</name>
                                //      </translation>
                                //    </translations>
                                //  </category>
                                //</categories>
                                #endregion

                                Uri addrKat = new Uri(kategoriXmlUrl);
                                bool KatSuccess = false;
                                string KatXMLContent = ConnectRestEC(addrKat, out KatSuccess);
                                XDocument xDocKat = XDocument.Parse(KatXMLContent.Replace("ISO-8859-9", "utf-8"));
                                List<GamaXmlCategory> gamaCategories = (from x in xDocKat.Descendants("category")
                                                                        select new GamaXmlCategory
                                                                        {
                                                                            active = x.Descendants("active").First().Value,
                                                                            categoryCode = x.Descendants("categoryCode").First().Value,
                                                                            parentCategoryCode = x.Descendants("parentCategoryCode").First().Value,
                                                                            desc = x.Descendants("translations").Descendants("translation").Descendants("desc").First().Value,
                                                                            languageCode = x.Descendants("translations").Descendants("translation").Descendants("languageCode").First().Value,
                                                                            name = x.Descendants("translations").Descendants("translation").Descendants("name").First().Value
                                                                        }).ToList();

                                //Marka Xml Get
                                #region Marka Sample XML
                                //<brands>
                                //  <brand>
                                //    <brandDesc/>
                                //    <active>1</active>
                                //    <brandCode>2</brandCode>
                                //    <brandName>CHIMEI</brandName>
                                //  </brand>
                                //</brands>
                                #endregion

                                Uri addrMar = new Uri(markaXmlUrl);
                                bool MarkSuccess = false;
                                string MarXMLContent = ConnectRestEC(addrMar, out MarkSuccess);
                                XDocument xDocMar = XDocument.Parse(MarXMLContent.Replace("ISO-8859-9", "utf-8"));
                                List<GamaXmlBrand> gamaBrands = (from x in xDocMar.Descendants("brand")
                                                                 select new GamaXmlBrand
                                                                 {
                                                                     brandDesc = x.Descendants("brandDesc").First().Value,
                                                                     active = x.Descendants("active").First().Value,
                                                                     brandCode = x.Descendants("brandCode").First().Value,
                                                                     brandName = x.Descendants("brandName").First().Value
                                                                 }).ToList();

                                //Fiyat Xml Get
                                #region Fiyat Sample XML
                                //<stockPrices>
                                //  <product productCode="05.083.0001">
                                //    <sellPrice>593,6</sellPrice>
                                //    <sellCurrency>USD</sellCurrency>
                                //    <buyPrice>535</buyPrice>
                                //    <buyCurrency>USD</buyCurrency>
                                //    <costPrice>0</costPrice>
                                //    <costCurrency>TL</costCurrency>
                                //    <marketPrice>0</marketPrice>
                                //    <marketCurrency>TL</marketCurrency>
                                //    <quantity>3</quantity>
                                //    <productVariants/>
                                //  </product>
                                //</stockPrices>
                                #endregion

                                Uri addrFiy = new Uri(fiyatXmlUrl);
                                bool FiySuccess = false;
                                string FiyXMLContent = ConnectRestEC(addrFiy, out FiySuccess);
                                XDocument xDocFiy = XDocument.Parse(FiyXMLContent.Replace("ISO-8859-9", "utf-8"));
                                List<GamaXmlStockPrice> gamaFiyatlar = (from x in xDocFiy.Descendants("product")
                                                                        select new GamaXmlStockPrice
                                                                        {
                                                                            productCode = x.Attributes("productCode").First().Value,
                                                                            sellPrice = x.Descendants("sellPrice").First().Value.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator),
                                                                            sellCurrency = x.Descendants("sellCurrency").First().Value,
                                                                            buyPrice = x.Descendants("buyPrice").First().Value.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator),
                                                                            buyCurrency = x.Descendants("buyCurrency").First().Value,
                                                                            costPrice = x.Descendants("costPrice").First().Value.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator),
                                                                            costCurrency = x.Descendants("costCurrency").First().Value,
                                                                            marketPrice = x.Descendants("marketPrice").First().Value.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator),
                                                                            marketCurrency = x.Descendants("marketCurrency").First().Value,
                                                                            quantity = x.Descendants("quantity").First().Value,
                                                                            productVariants = x.Descendants("productVariants").First().Value
                                                                        }).ToList();

                                //Ekstra Özellik Get
                                #region Ekstra Özellik Sample XML
                                //<productProperties>
                                //  <product productCode="05.083.0001">
                                //    <productProperty>
                                //      <active>1</active>
                                //      <propertyGroupCode>100</propertyGroupCode>
                                //      <propertyCode>4550005</propertyCode>
                                //      <value>OKI ML3320 9 PIN 80 KOLON(435 CPS)</value>
                                //    </productProperty>
                                //    <productProperty>
                                //      <active>1</active>
                                //      <propertyGroupCode>100</propertyGroupCode>
                                //      <propertyCode>4550005</propertyCode>
                                //      <value>OKI ML3320 9 PIN 80 KOLON(435 CPS)</value>
                                //    </productProperty>
                                //  </product>
                                //</productProperties>
                                #endregion

                                Uri addrproProp = new Uri(productPropertyXmlUrl);
                                bool proPropSuccess = false;
                                string proPropXMLContent = ConnectRestEC(addrproProp, out proPropSuccess);
                                XDocument xDocproProp = XDocument.Parse(proPropXMLContent.Replace("ISO-8859-9", "utf-8"));
                                List<GamaXmlProductProperty> gamaproProp = (from x in xDocproProp.Descendants("product").Descendants("productProperty")
                                                                            select new GamaXmlProductProperty
                                                                        {
                                                                            productCode = x.Parent.Attributes("productCode").First().Value,
                                                                            active = x.Descendants("active").First().Value,
                                                                            propertyGroupCode = x.Descendants("propertyGroupCode").First().Value,
                                                                            propertyCode = x.Descendants("propertyCode").First().Value,
                                                                            value = x.Descendants("value").First().Value
                                                                        }).ToList();

                                //Ekstra Özellik Detay Get
                                #region Ekstra Özellik Detay Sample XML
                                //<properties>
                                //  <property>
                                //    <code>10050402</code>
                                //    <active>1</active>
                                //    <groupCode>100</groupCode>
                                //    <categoryCode>50402</categoryCode>
                                //    <translations>
                                //      <translation>
                                //        <languageCode>TUR</languageCode>
                                //        <name>Erişim Süresi</name>
                                //        <desc>Erişim Süresi</desc>
                                //      </translation>
                                //    </translations>
                                //  </property>
                                //</properties>
                                #endregion

                                Uri addrproPropd = new Uri(propertyXmlUrl);
                                bool proPropdSuccess = false;
                                string proPropdXMLContent = ConnectRestEC(addrproPropd, out proPropdSuccess);
                                XDocument xDocproPropd = XDocument.Parse(proPropdXMLContent.Replace("ISO-8859-9", "utf-8"));
                                List<GamaXmlProperty> gamaproPropDetails = (from x in xDocproPropd.Descendants("property")
                                                                            select new GamaXmlProperty
                                                                            {
                                                                                code = x.Descendants("code").First().Value,
                                                                                active = x.Descendants("active").First().Value,
                                                                                groupCode = x.Descendants("groupCode").First().Value,
                                                                                categoryCode = x.Descendants("categoryCode").First().Value,
                                                                                languageCode = x.Descendants("translations").Descendants("translation").Descendants("languageCode").First().Value,
                                                                                name = x.Descendants("translations").Descendants("translation").Descendants("name").First().Value,
                                                                                desc = x.Descendants("translations").Descendants("translation").Descendants("desc").First().Value
                                                                            }).ToList();

                                #endregion

                                List<XElement> productList = xDoc.Descendants("products").Descendants("product").ToList();
                                Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                                dbProduct.ResetAmount(xml.XmlIdForProductId);
                                Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                                foreach (var product in productList)
                                {
                                    productCounterr++;
                                    if (productCounterr == 261 || productCounterr == 693)
                                    {
                                        continue;
                                    }
                                    #region Sample XML
                                    //<products>
                                    //  <product productCode="05.083.0001">
                                    //    <categoryCode>50005</categoryCode>
                                    //    <productType>208</productType>
                                    //    <stockCode>05.083.0001</stockCode>
                                    //    <brandCode>89</brandCode>
                                    //    <active>1</active>
                                    //    <taxFree>0</taxFree>
                                    //    <taxes>
                                    //      <tax>
                                    //        <taxName>KDV</taxName>
                                    //        <taxRate>18</taxRate>
                                    //        <taxIncluded>0</taxIncluded>
                                    //      </tax>
                                    //    </taxes>
                                    //    <translations>
                                    //      <translation>
                                    //        <name>OKI ML3320 9 PIN 80 KOLON(435 CPS)</name>
                                    //        <desc>Lorem ipsum dolor sit amet</desc>
                                    //        <languageCode>TUR</languageCode>
                                    //      </translation>
                                    //    </translations>
                                    //    <pictures>
                                    //      <picture>
                                    //        <path>http://bayi.e-gama.com/emails/productimages/resim28_1.jpg</path>
                                    //        <isDefault>1</isDefault>
                                    //        <active>1</active>
                                    //        <translations>
                                    //          <translation>
                                    //            <alternateText>OKI ML3320 9 PIN 80 KOLON(435 CPS)</alternateText>
                                    //            <languageCode>TUR</languageCode>
                                    //          </translation>
                                    //        </translations>
                                    //      </picture>
                                    //    </pictures>
                                    //  </product>
                                    //</products>
                                    #endregion

                                    #region Processed Product Count Log

                                    ProductCount++;
                                    if (ProductCount % 100 == 0)
                                    {
                                        Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                    }

                                    #endregion

                                    //sıfır kontrol

                                    ProcessedProductCode = XEAttributeResultString(product, "productCode");


                                    int gamacategoryID = XEResultInt(product, "categoryCode");
                                    int gamaBrandId = XEResultInt(product, "brandCode");
                                    string groupname = "CatNotFound";
                                    string groupnameMain = "";
                                    string brand = "BrandNotFound";

                                    var kQuery = gamaCategories.Where(o => o.categoryCode != null && o.categoryCode == gamacategoryID.ToString()).ToList();
                                    if (kQuery.Count() > 0)
                                    {
                                        groupname = kQuery.FirstOrDefault().name;
                                        if (kQuery.FirstOrDefault().parentCategoryCode != "0")
                                        {
                                            var mcQuery = gamaCategories.Where(o => o.categoryCode != null && o.categoryCode == kQuery.FirstOrDefault().parentCategoryCode).ToList();
                                            if (mcQuery.Count() > 0)
                                            {
                                                groupnameMain = mcQuery.FirstOrDefault().name + " - ";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        kategoriSifir += ProcessedProductCode + ", ";
                                        continue;
                                    }

                                    string groupname2 = gamacategoryID.ToString() + '-' + groupnameMain + groupname;
                                    var mQuery = gamaBrands.Where(o => o.brandCode == gamaBrandId.ToString()).ToList();
                                    if (mQuery.Count() > 0)
                                    {
                                        brand = gamaBrands.Where(o => o.brandCode == gamaBrandId.ToString()).FirstOrDefault().brandName;
                                    }
                                    else
                                    {
                                        markaSifir += ProcessedProductCode + ", ";
                                        continue;
                                    }



                                    #region Category Group Control

                                    XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                    if (xmlImportGroup2 == null)
                                    {
                                        int altGrupId = dbCategory.GetByName(groupname);

                                        Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                        if (altGrupId > 0)
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                        }
                                        xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                        sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                    }
                                    Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                    if (!xmlImportGroup2.IsActive || category2 == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    #region Brand Control

                                    XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    if (xmlBrand == null)
                                    {
                                        int brandId = dbCategory.GetByName(brand);

                                        Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                        if (brandId > 0)
                                        {
                                            dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                            xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                            continue;
                                        }
                                        sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                    }
                                    Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                    if (!xmlBrand.IsActive || brandGroup == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    #region Vars

                                    if (string.IsNullOrEmpty(ProcessedProductCode))
                                    {
                                        continue;
                                    }
                                    string DealerProductId = ProcessedProductCode;
                                    string ProductId = XEResultString(product, "stockCode");
                                    string ImageUrl = XEResultString(product, "path");
                                    string Description = HttpUtility.HtmlDecode(XEResultString(product, "desc"));
                                    string Tax = XEResultString(product, "taxRate");
                                    string ProductName = XEResultString(product, "name");
                                    //if (ProductName.Length > 65)
                                    //{
                                    //    ProductName = ProductName.Substring(0, 64);
                                    //}
                                    decimal Price = 0;
                                    var pQuery = gamaFiyatlar.Where(o => o.productCode == ProcessedProductCode).ToList();
                                    if (pQuery.Count() > 0)
                                    {
                                        Price = Convert.ToDecimal(gamaFiyatlar.Where(o => o.productCode == ProcessedProductCode).FirstOrDefault().sellPrice);
                                    }
                                    else
                                    {
                                        fiyatSifir += ProcessedProductCode + ", ";
                                        continue;
                                    }
                                    decimal Amount = Convert.ToDecimal(gamaFiyatlar.Where(o => o.productCode == ProcessedProductCode).FirstOrDefault().quantity);
                                    decimal AmountOnRoad = 0;
                                    decimal BuyingPrice = Convert.ToDecimal(gamaFiyatlar.Where(o => o.productCode == ProcessedProductCode).FirstOrDefault().buyPrice);
                                    string Barcode = XEResultString(product, "stockCode");
                                    string Currency = gamaFiyatlar.Where(o => o.productCode == ProcessedProductCode).FirstOrDefault().buyCurrency;
                                    //int xmlBrandId = xmlBrand.Id;
                                    //int xmlGroupId = xmlImportGroup2.Id;

                                    Tax = Tax.Replace("0.", "");

                                    if (BuyingPrice > 0)
                                    {
                                        Price = Math.Round(BuyingPrice * xmlBrand.ProfitRate, 2);
                                    }
                                    else
                                    {
                                        Price = Math.Round(Price * xml.ProfitRate, 2);
                                    }

                                    //if (Parameters.SetPricesWithoutTax)
                                    //{
                                    //    Price = Price * (1 + (decimal.Parse(Tax) / 100));
                                    //    BuyingPrice = BuyingPrice * (1 + (decimal.Parse(Tax) / 100));
                                    //}

                                    if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                    {
                                        Price += xml.PriceToAdd;
                                    }
                                    if (xml.PriceToAddAll > 0)
                                    {
                                        Price += xml.PriceToAddAll;
                                    }

                                    short DeliveryTime = xml.DeliveryTime;
                                    decimal Desi = 0;
                                    if (xmlImportGroup2.Desi == 0)
                                    {
                                        Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                    }
                                    else
                                    {
                                        Desi = xmlImportGroup2.Desi;
                                    }

                                    decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                    bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                    bool FastCargo = true;
                                    if (Amount == 0)
                                    {
                                        Amount = xml.Amount;
                                        if (Amount == 0)
                                        {
                                            FastCargo = false;
                                        }
                                    }
                                    if (AmountOnRoad == 0)
                                    {
                                        AmountOnRoad = xml.AmountOnRoad;
                                    }

                                    #endregion

                                    int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                    if (productId == -2)
                                    {
                                        productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                        if (productId > 0)
                                        {
                                            dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                        }
                                        continue;
                                    }
                                    bool NewProduct = false;
                                    if (productId == -1 && xml.InsertNewProduct)
                                    {
                                        //Logger.Write("XML Import Product Insert : " + ProductId + " - " + ProductName, "Trace");

                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                      Description, xml.ReloadDescription, false, 0, "Yıl", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                        NewProduct = true;
                                        newProductCounter++;
                                    }
                                    else
                                    {
                                        if (xml.StkNameNotUpdate)
                                        {
                                            productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                      Description, xml.ReloadDescription, false, 0, "Yıl", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                        }
                                        else
                                        {
                                            productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                      Description, xml.ReloadDescription, false, 0, "Yıl", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                        }
                                    }
                                    if (NewProduct || xml.ReInstallProductImg)
                                    {
                                        #region New Product to Update Image

                                        if (productId > 0 && !string.IsNullOrEmpty(ImageUrl))
                                        {
                                            Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, 1);
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }

                                        #endregion
                                    }
                                    if (productId > 0)
                                    {
                                        #region Stok Kart Ekstra Alanlar

                                        foreach (var productinfo in gamaproProp.Where(o => o.productCode == ProcessedProductCode && o.active == "1"))
                                        {
                                            string type = HttpUtility.HtmlDecode(gamaproPropDetails.Where(x => x.code == productinfo.propertyCode).First().name);
                                            string Information = HttpUtility.HtmlDecode(productinfo.value);

                                            dbProductInfo.Insert(productId, type, Information);
                                        }

                                        string typee = "Diğer";
                                        string Informationn = groupname;
                                        dbProductInfo.Insert(productId, typee, Informationn);

                                        #endregion

                                        #region Stok Kart Ekstra Gruplar

                                        foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                        {
                                            dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                        }

                                        #endregion
                                    }

                                }

                                //var xdfgh = "asdsds";
                                #endregion
                            }
                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("DILAY") || xml.Description.ToUpperInvariant().Contains("DİLAY"))
                        {
                            #region DİLAY KOZMETİK

                            List<XElement> productList = xDoc.Descendants("Products").Descendants("Product").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {
                                #region tedarik kurtar
                                ////lazım olanlar: ok KRTID, ok XMLID, ok XMLKARTID, ok XMLKARTKOD, ok XMLKARTBARKOD, ok ALISFIYATI, ok STOKMIKTAR, ok STOKMIKTARYOLDA, ok GUNCELLE
                                //string PName = XEResultString(product, "ModelName");
                                //if (PName.Length > 65)
                                //{
                                //    PName = PName.Substring(0, 64);
                                //}
                                //int pId = dbProduct.GetProductIdByProductName(PName);
                                //if (pId > 0)
                                //{
                                //    string xpId = XEResultString(product, "ProductID");
                                //    decimal xBuyingPrice = XEResultDecimal(product, "BuyingPrice", xml.DecimalPoint);
                                //    decimal xAmount = XEResultDecimal(product, "UnitInStock", xml.DecimalPoint);
                                //    decimal xAmountOnRoad = XEResultDecimal(product, "AmountOnRoad", xml.DecimalPoint);

                                //    int xxProId = dbProduct.insertStokKartSaticiByName(pId, xml.XmlId, xpId, xpId, xpId, xBuyingPrice, xAmount, xAmountOnRoad, 1);
                                //    olanlar++;
                                //    if(olanlar==425){
                                //        olanlar = olanlar+0;
                                //    }
                                //}
                                //else
                                //{
                                //    olmayanlar++;
                                //}

                                //continue;

                                #endregion

                                #region Sample XML
                                /*
                                 <Products>
                                    <Product>
                                      <CategoryCode /> 
                                      <CategoryID>12083</CategoryID> 
                                      <CategoryName>Rimeller</CategoryName> 
                                      <ParentCategoryCode /> 
                                      <ParentCategoryID>11995</ParentCategoryID> 
                                      <ParentCategoryName>G��akyaj��arentCategoryName> 
                                      <CategoryPath>G��akyaj��Rimeller</CategoryPath> 
                                      <ProductID>87474</ProductID> 
                                      <SKU>4144</SKU> 
                                      <Manufacture>Loreal Paris</Manufacture> 
                                      <ModelNumber>2746</ModelNumber> 
                                      <ModelName>Loreal Paris Mascara Voluminous x4 - Dolgunla����Rimel</ModelName> 
                                      <ListPrice>33.8898</ListPrice> 
                                      <Price>30.3729</Price> 
                                      <BuyingPrice>24.3000</BuyingPrice> 
                                      <KDVPrice>35.8400</KDVPrice> 
                                      <EFTPrice>34.0480</EFTPrice> 
                                      <KDV>0.18</KDV> 
                                      <CurrencyType>TRL</CurrencyType> 
                                      <Description /> 
                                      <Image>http://www.dilaykozmetik.com/ProductImages/87474/cos34.jpg</Image> 
                                      <BigImage>http://www.dilaykozmetik.com/ProductImages/87474/Bcos34.jpg</BigImage> 
                                      <UnitInStock>6</UnitInStock> 
                                      <InStock>True</InStock> 
                                      <IsEnabled>True</IsEnabled> 
                                      <ShippingVolume>1</ShippingVolume> 
                                      <DetailLink>http://www.dilaykozmetik.com/urun/loreal-paris-mascara-voluminous-x4---dolgunlastirici-rimel-.aspx</DetailLink> 
                                      </Product>
                                    <Product>
                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                int categoryID = XEResultInt(product, "CategoryID");
                                string groupname = XEResultString(product, "CategoryName");
                                string groupname2 = categoryID.ToString() + '-' + groupname;
                                string brand = XEResultString(product, "Manufacture");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                ProcessedProductCode = XEResultString(product, "SKU");
                                string DealerProductId = ProcessedProductCode;
                                string ProductId = XEResultString(product, "ProductID");
                                string ImageUrl = XEResultString(product, "ImageURL");
                                /*middle ayarlama!!*/
                                ImageUrl = ImageUrl.Replace("/big/", "/middle/");
                                /*middle ayarlama!!*/
                                string Description = HttpUtility.HtmlDecode(XEResultString(product, "Description"));
                                string Tax = XEResultString(product, "KDV");
                                string ProductName = XEResultString(product, "ModelName");
                                if (ProductName.Length > 65)
                                {
                                    ProductName = ProductName.Substring(0, 64);
                                }
                                decimal Price = XEResultDecimal(product, "Price", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "UnitInStock", xml.DecimalPoint);
                                decimal AmountOnRoad = XEResultDecimal(product, "AmountOnRoad", xml.DecimalPoint);
                                decimal BuyingPrice = XEResultDecimal(product, "BuyingPrice", xml.DecimalPoint);
                                string Barcode = XEResultString(product, "ModelNumber");
                                string Currency = ChangeExchangeCode(XEResultString(product, "CurrencyType"));
                                //int xmlBrandId = xmlBrand.Id;
                                //int xmlGroupId = xmlImportGroup2.Id;

                                Tax = Tax.Replace("0.", "");

                                if (BuyingPrice > 0)
                                {
                                    Price = Math.Round(BuyingPrice * xmlBrand.ProfitRate, 2);
                                }
                                else
                                {
                                    Price = Math.Round(Price * xml.ProfitRate, 2);
                                }
                                //if (Parameters.SetPricesWithoutTax)
                                //{
                                //    Price = Price * (1 + (decimal.Parse(Tax) / 100));
                                //    BuyingPrice = BuyingPrice * (1 + (decimal.Parse(Tax) / 100));
                                //}

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                short DeliveryTime = xml.DeliveryTime;
                                decimal Desi = 0;
                                if (xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }

                                decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                bool FastCargo = true;
                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }

                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }
                                bool NewProduct = false;
                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    //Logger.Write("XML Import Product Insert : " + ProductId + " - " + ProductName, "Trace");

                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                              Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                              Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                }
                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0 && !string.IsNullOrEmpty(ImageUrl))
                                    {
                                        Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                        try
                                        {
                                            DownloadImage(productId, ImageUrl, 1);
                                        }
                                        catch
                                        {
                                            Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                            sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                        }
                                    }

                                    #endregion
                                }
                                if (productId > 0)
                                {
                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("OMAY") && !xml.Description.ToUpperInvariant().Contains("BAYİ") && !xml.Description.ToUpperInvariant().Contains("BAYI"))
                        {
                            #region OMAY

                            List<XElement> productList = xDoc.Descendants("MerchantItems").Descendants("MerchantItem").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {
                                #region Sample XML
                                /*
                                    <MerchantItem>
                                    <merchantItemId>{Id}</merchantItemId>
                                    <merchantItemCode><![CDATA[{ProductCode}]]></merchantItemCode>
                                    <merchantItemCategoryId>{CategoryId}</merchantItemCategoryId>
                                    <merchantItemCategoryName><![CDATA[{Category}]]></merchantItemCategoryName>
                                    <brand><![CDATA[{Brand}]]></brand>
                                    <model><![CDATA[{Model}]]></model>
                                    <itemTitle><![CDATA[{Name}]]></itemTitle>
                                    <merchantItemField>{Cargo}</merchantItemField>
                                    <image_url><![CDATA[{ImageURL}]]></image_url>
                                    <tax>{Tax}</tax>
                                    <price>{Price}</price> 
                                    <currency>{Currency}</currency>
                                    <description><![CDATA[{Description}]]></description>                                     
                                    <warantyPeriod>{WarantyPeriod}</warantyPeriod>
                                    <warantyTime>{WarantyTime}</warantyTime>
                                    <deliveryPeriod>{DeliveryPeriod}</deliveryPeriod>
                                    <deliveryTime>{DeliveryTime}</deliveryTime> 
                                    <cargoPriceField>{CargoPriceField}</cargoPriceField>
                                    <cargoPriceAddition>{CargoPriceAdditionField}</cargoPriceAddition>
                                    <freeCargo>{FreeCargo}</freeCargo>
                                    <fastCargo>{FastCargo}</fastCargo>
                                    <newProduct>{NewProduct}</newProduct>  
                                    <desi>{Desi}</desi>
                                    <weight>{Weight}</weight>
                                    <width>{Width}</width>
                                    <length>{Length}</length>
                                    <height>{Height}</height>
                                     
                                     
                                    <itemUrl><![CDATA[{Url}]]></itemUrl>
                                    <price3T/>
                                    <price6T/>
                                    <price12T/>
                                    <price24T/>
                                    <priceEft>{PriceWithTransfer}</priceEft>
                                    <pricePlusTax>{PriceWithTax}</pricePlusTax>                                    

                                    {Extra}
                                    </MerchantItem>
                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                ProcessedProductCode = XEResultString(product, "merchantItemCode");
                                Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                int categoryID = XEResultInt(product, "merchantItemCategoryId");
                                string groupname = XEResultString(product, "merchantItemCategoryName");
                                string groupname2 = categoryID.ToString() + '-' + groupname;
                                string brand = XEResultString(product, "brand");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                string ProductCode = ProcessedProductCode;
                                string ProductId = XEResultString(product, "merchantItemId");
                                string Model = XEResultString(product, "model");
                                string ProductName = XEResultString(product, "itemTitle");
                                string CargoDescription = XEResultString(product, "merchantItemField");
                                string ImageUrl = XEResultString(product, "image_url");
                                decimal Tax = XEResultDecimal(product, "tax", xml.DecimalPoint);
                                decimal Price = XEResultDecimal(product, "price", xml.DecimalPoint);
                                decimal BuyingPrice = XEResultDecimal(product, "buyingprice", xml.DecimalPoint);
                                string Currency = ChangeExchangeCode(XEResultString(product, "currency"));
                                string Description = XEResultString(product, "description");
                                string WarantyPeriod = XEResultString(product, "warantyPeriod");
                                int WarantyTime = XEResultInt(product, "warantyTime");
                                string DeliveryPeriod = XEResultString(product, "deliveryPeriod");
                                int DeliveryTime = XEResultInt(product, "deliveryTime");
                                decimal CargoPriceField = XEResultDecimal(product, "cargoPriceField", xml.DecimalPoint);
                                decimal CargoPriceAdditionField = XEResultDecimal(product, "cargoPriceAdditionField", xml.DecimalPoint);
                                bool FreeCargo = XEResultBool(product, "freeCargo");
                                bool FastCargo = XEResultBool(product, "fastCargo");
                                bool NewProduct = XEResultBool(product, "newProduct");
                                decimal Desi = XEResultDecimal(product, "desi", xml.DecimalPoint);
                                decimal Weight = XEResultDecimal(product, "weight", xml.DecimalPoint);
                                decimal Width = XEResultDecimal(product, "width", xml.DecimalPoint);
                                decimal Length = XEResultDecimal(product, "length", xml.DecimalPoint);
                                decimal Height = XEResultDecimal(product, "height", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "amount", xml.DecimalPoint);
                                decimal AmountOnRoad = 0;

                                Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    AmountOnRoad = xml.AmountOnRoad;
                                }

                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }
                                if (productId == -1)
                                {
                                    if (xml.InsertNewProduct)
                                    {
                                        Logger.Write("Product Insert : " + ProductId + " - " + ProductName, "Trace");

                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad);

                                        Logger.Write("Product Inserted : ProductId => " + productId.ToString(), "Trace");
                                        newProductCounter++;

                                        #region New Product to Update Image

                                        if (productId > 0 && !string.IsNullOrEmpty(ImageUrl))
                                        {
                                            Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, 1);
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }

                                        #endregion
                                    }
                                }
                                else
                                {
                                    Logger.Write("Product Update : " + productId.ToString() + " " + ProductId + " - " + ProductName, "Trace");
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode,
                                                                  category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                  category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    Logger.Write("Product Updated : ProductId => " + productId.ToString(), "Trace");
                                }

                                if (productId > 0)
                                {
                                    #region Stok Kart Ekstra Alanlar

                                    foreach (var productinfo in product.Descendants("uniqueCodeArea").Descendants("uniqueCode"))
                                    {
                                        string type = XEResultString(productinfo, "uniqueCodeType");
                                        string Information = XEResultString(productinfo, "uniqueCodeValue");

                                        dbProductInfo.Insert(productId, type, Information);
                                    }

                                    #endregion

                                    #region Stok Kart Ekstra Gruplar

                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }

                                    #endregion
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("OMAY") &&
                                (xml.Description.ToUpperInvariant().Contains("BAYİ") || xml.Description.ToUpperInvariant().Contains("BAYI")))
                        {
                            #region OMAY BAYİ

                            List<XElement> productList = xDoc.Descendants("MerchantItems").Descendants("MerchantItem").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {
                                #region Sample XML
                                /*
                                    <MerchantItem>
                                    <merchantItemId>{Id}</merchantItemId>
                                    <merchantItemCode><![CDATA[{ProductCode}]]></merchantItemCode>
                                    <merchantItemCategoryId>{CategoryId}</merchantItemCategoryId>
                                    <merchantItemCategoryName><![CDATA[{Category}]]></merchantItemCategoryName>
                                    <brand><![CDATA[{Brand}]]></brand>
                                    <model><![CDATA[{Model}]]></model>
                                    <itemTitle><![CDATA[{Name}]]></itemTitle>
                                    <merchantItemField>{Cargo}</merchantItemField>
                                    <image_url><![CDATA[{ImageURL}]]></image_url>
                                    <tax>{Tax}</tax>
                                    <price>{Price}</price>
                                    <buyingprice>{BuyingPrice}<buyingprice>
                                    <currency>{Currency}</currency>
                                    <description><![CDATA[{Description}]]></description>                                     
                                    <warantyPeriod>{WarantyPeriod}</warantyPeriod>
                                    <warantyTime>{WarantyTime}</warantyTime>
                                    <deliveryPeriod>{DeliveryPeriod}</deliveryPeriod>
                                    <deliveryTime>{DeliveryTime}</deliveryTime> 
                                    <cargoPriceField>{CargoPriceField}</cargoPriceField>
                                    <cargoPriceAddition>{CargoPriceAdditionField}</cargoPriceAddition>
                                    <freeCargo>{FreeCargo}</freeCargo>
                                    <fastCargo>{FastCargo}</fastCargo>
                                    <newProduct>{NewProduct}</newProduct>  
                                    <desi>{Desi}</desi>
                                    <weight>{Weight}</weight>
                                    <width>{Width}</width>
                                    <length>{Length}</length>
                                    <height>{Height}</height>
                                     
                                     
                                    <itemUrl><![CDATA[{Url}]]></itemUrl>
                                    <price3T/>
                                    <price6T/>
                                    <price12T/>
                                    <price24T/>
                                    <priceEft>{PriceWithTransfer}</priceEft>
                                    <pricePlusTax>{PriceWithTax}</pricePlusTax>                                    

                                    {Extra}
                                    </MerchantItem>
                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                int categoryID = XEResultInt(product, "merchantItemCategoryId");
                                string groupname = XEResultString(product, "merchantItemCategoryName");
                                string groupname2 = categoryID.ToString() + '-' + groupname;
                                string brand = XEResultString(product, "brand");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                ProcessedProductCode = XEResultString(product, "merchantItemCode");
                                string ProductCode = ProcessedProductCode;
                                string ProductId = XEResultString(product, "merchantItemId");
                                string Model = XEResultString(product, "model");
                                string ProductName = XEResultString(product, "itemTitle");
                                string CargoDescription = XEResultString(product, "merchantItemField");
                                string ImageUrl = XEResultString(product, "image_url");
                                decimal Tax = XEResultDecimal(product, "tax", xml.DecimalPoint);
                                decimal Price = XEResultDecimal(product, "price", xml.DecimalPoint);
                                decimal BuyingPrice = XEResultDecimal(product, "buyingprice", xml.DecimalPoint);
                                string Currency = ChangeExchangeCode(XEResultString(product, "currency"));
                                string Description = XEResultString(product, "description");
                                string WarantyPeriod = XEResultString(product, "warantyPeriod");
                                int WarantyTime = XEResultInt(product, "warantyTime");
                                string DeliveryPeriod = XEResultString(product, "deliveryPeriod");
                                int DeliveryTime = XEResultInt(product, "deliveryTime");
                                decimal CargoPriceField = XEResultDecimal(product, "cargoPriceField", xml.DecimalPoint);
                                decimal CargoPriceAdditionField = XEResultDecimal(product, "cargoPriceAdditionField", xml.DecimalPoint);
                                bool FreeCargo = XEResultBool(product, "freeCargo");
                                bool FastCargo = XEResultBool(product, "fastCargo");
                                bool NewProduct = XEResultBool(product, "newProduct");
                                decimal Desi = XEResultDecimal(product, "desi", xml.DecimalPoint);
                                decimal Weight = XEResultDecimal(product, "weight", xml.DecimalPoint);
                                decimal Width = XEResultDecimal(product, "width", xml.DecimalPoint);
                                decimal Length = XEResultDecimal(product, "length", xml.DecimalPoint);
                                decimal Height = XEResultDecimal(product, "height", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "amount", xml.DecimalPoint);
                                decimal AmountOnRoad = 0;

                                if (BuyingPrice > 0)
                                {
                                    Price = Math.Round(BuyingPrice * xmlBrand.ProfitRate, 2);
                                }
                                else
                                {
                                    Price = Math.Round(Price * xml.ProfitRate, 2);
                                }

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    AmountOnRoad = xml.AmountOnRoad;
                                }

                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }
                                if (productId == -1)
                                {
                                    if (xml.InsertNewProduct)
                                    {
                                        Logger.Write("XML Import Product Insert : " + ProductId + " - " + ProductName, "Trace");

                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad);

                                        Logger.Write("XML Import Product Insert : ProductId => " + productId.ToString(), "Trace");
                                        newProductCounter++;

                                        #region New Product to Update Image

                                        if (productId > 0 && !string.IsNullOrEmpty(ImageUrl))
                                        {
                                            Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, 1);
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }

                                        #endregion
                                    }
                                }
                                else
                                {
                                    Logger.Write("XML Import Product Update : " + productId.ToString() + " " + ProductId + " - " + ProductName, "Trace");
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode,
                                                                  category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                     category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                     Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                     false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                     Width, Length, Height, Weight, Desi,
                                                                     FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                     true, Model, Amount, AmountOnRoad);
                                    }
                                }

                                if (productId > 0)
                                {
                                    #region Stok Kart Ekstra Alanlar

                                    foreach (var productinfo in product.Descendants("uniqueCodeArea").Descendants("uniqueCode"))
                                    {
                                        string type = XEResultString(productinfo, "uniqueCodeType");
                                        string Information = XEResultString(productinfo, "uniqueCodeValue");

                                        dbProductInfo.Insert(productId, type, Information);
                                    }

                                    #endregion

                                    #region Stok Kart Ekstra Gruplar

                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }

                                    #endregion
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("ARAL") && xml.Description.ToUpperInvariant().Contains("GAME"))
                        {
                            #region ARAL GAME

                            //merge xmls

                            List<string> xmlUrlList = new List<string>();
                            xmlUrlList.Add(xml.Url);
                            xmlUrlList.Add("http://www.aralgame.com/websatis/kampanya_kdvsiz.php");
                            List<AralXmlProducts> aralProducts = new List<AralXmlProducts>();
                            foreach (var xmlImportUrl in xmlUrlList)
                            {
                                Uri aralXmlUrl = new Uri(xmlImportUrl);
                                bool aralXmlSuccess = false;
                                string aralXMLContent = ConnectRestEC(aralXmlUrl, out aralXmlSuccess);
                                XDocument xDocAral = XDocument.Parse(aralXMLContent);
                                List<AralXmlProducts> products = (from x in xDocAral.Descendants("Product")
                                                                  select new AralXmlProducts
                                                                  {
                                                                      ProductNo = x.Descendants("ProductNo").Count() < 1 ? "" : x.Descendants("ProductNo").FirstOrDefault().Value,
                                                                      ProductName = x.Descendants("ProductName").Count() < 1 ? "" : x.Descendants("ProductName").FirstOrDefault().Value,
                                                                      Category = x.Descendants("Category").Count() < 1 ? "" : x.Descendants("Category").FirstOrDefault().Value,
                                                                      ParentCategory = x.Descendants("ParentCategory").Count() < 1 ? "" : x.Descendants("ParentCategory").FirstOrDefault().Value,
                                                                      SubCategory = x.Descendants("SubCategory").Count() < 1 ? "" : x.Descendants("SubCategory").FirstOrDefault().Value,
                                                                      Attribute = x.Descendants("Attribute").Count() < 1 ? "" : x.Descendants("Attribute").FirstOrDefault().Value,
                                                                      Brand = x.Descendants("Brand").Count() < 1 ? "" : x.Descendants("Brand").FirstOrDefault().Value,
                                                                      Price = x.Descendants("Price").Count() < 1 ? "" : x.Descendants("Price").FirstOrDefault().Value.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator),
                                                                      Currency = x.Descendants("Currency").Count() < 1 ? "" : x.Descendants("Currency").FirstOrDefault().Value,
                                                                      Tax = x.Descendants("Tax").Count() < 1 ? "" : x.Descendants("Tax").FirstOrDefault().Value,
                                                                      Image = x.Descendants("Image").Count() < 1 ? "" : x.Descendants("Image").FirstOrDefault().Value,
                                                                      Details = x.Descendants("Details").Count() < 1 ? "" : x.Descendants("Details").FirstOrDefault().Value,
                                                                      Barcode = x.Descendants("Barcode").Count() < 1 ? "" : x.Descendants("Barcode").FirstOrDefault().Value,
                                                                      Stock = x.Descendants("Stock").Count() < 1 ? "" : x.Descendants("Stock").FirstOrDefault().Value,
                                                                      CategoryAddition = xmlImportUrl.ToUpperInvariant().Contains("KAMPANYA") ? "Kampanya" : ""
                                                                  }).ToList();

                                aralProducts.AddRange(products);
                            }
                            //merge xmls

                            //List<XElement> productList = xDoc.Descendants("Products").Descendants("Product").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + aralProducts.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            List<AralXmlProducts> boslar = aralProducts.Where(k => k.Brand == null || k.Brand == "").ToList<AralXmlProducts>();

                            var strBos = "";
                            foreach (var bos in boslar)
                            {
                                strBos += bos.ProductName + ", ";
                            }



                            foreach (var product in aralProducts)
                            {
                                if (product.ProductName.ToUpperInvariant().Contains("RIVALS") || product.ProductName.ToUpperInvariant().Contains("RİVALS") || product.ProductName.ToUpperInvariant().Contains("NFS") || product.ProductName.ToUpperInvariant().Contains("NEED FOR SPEED"))
                                {
                                    //test
                                }

                                #region Sample XML OLD

                                //<products>
                                //    <product>
                                //        <stockCode>00.6015</stockCode>
                                //        <name>PSX3 KILLZONE 2</name>
                                //        <price>30.00</price>
                                //        <cur>TL</cur>
                                //        <tax>18</tax>
                                //        <picture1>
                                //        http://www.aralgame.com//static/products/detail/2012-06/00.6015.jpg.jpg
                                //        </picture1>
                                //        <details>
                                //        <![CDATA[
                                //        "Hayatınızda gördüğünüz en korkunç savaş alanına girin. Guerrilla Games tarafından sadece PLAYSTATION® 3 için geliştirilen Killzone 2 uzun zamandır beklenen bir birinci şahıs nişancı (FPS) oyunu. Sonuç ise oyuncuları, PS3 kurulumunun hakkını veren oldukça detaylı, ultra gerçekçi bir savaş alanına götürmesi. PlayStation® 2 için yaratılan orijinal Killzone'daki olay ve aksiyonu takip eden oyunda, Vekta'ya yapılan Helghast saldırısından 2 yıl sonra ISA savaşı, düşmanın asıl evi olan Helghan'a götürüyor. ISA'nın hedefi gayet açık: Helghast lideri İmparator Visari'yi ele geçirip Helghast savaş makinasını durdurmak. Deneyimli bir savaşçı ve Legion özel kuvvetler timinin bir üyesi olan Sev karakteri altında oyuncular, görevi Helghast tehdidini savuştumak olan bir grup oldukça eğitimli askeri yönetecek. Sev ve takımı için Helghan istilası sadece bir başlangıç. Görevi başkent Pyrrhus'u ele geçirmek olan ekip, Helghast'ların kendi gezegenlerinde çok kuvvetli bir düşman olduklarını anlamakta gecikmez. Helghast'lar hem gezegenin kötü şartlarına uyum sağlamış hem de ISA'ya karşı kullanabilecekleri bir güç kaynağı geliştirmiştir. Sev takımının sadece düşman kuvvetlerine karşı değil daha da kötüsü gezegenin kendisine karşı savaşmak zorunda olduğunu anlamıştır. "
                                //        ]]>
                                //        </details>

                                //        <parentCategory>Oyun</parentCategory>
                                //        <category>PS3</category>
                                //        <subCategory>Aksiyon</subCategory>
                                //        <brand>SONY</brand>

                                //        <stock/>

                                //        <desi>-</desi>
                                //        <guarantee>-</guarantee>
                                //        <buyingPrice>-</buyingPrice>
                                //        <is_preorder>false</is_preorder>

                                //        </product>
                                //  </products>


                                #endregion

                                #region Sample XML

                                //<Products>
                                //    <Product>
                                //        <ProductName>
                                //        <![CDATA[ PSX3 MOTORSTORM APOCALYPSE ]]>
                                //        </ProductName>
                                //        <ProductNo>00.6052</ProductNo>
                                //        <Price>59.32</Price>
                                //        <Currency>TL</Currency>
                                //        <Tax>18</Tax>
                                //        <Image>
                                //        http://www.aralgame.com//static/products/detail/2012-06/00.6052.jpg.jpg
                                //        </Image>
                                //        <Details>
                                //        <![CDATA[
                                //        MotorStorm festivali Monument Valley'i, bir Pasifik Adasını ve Kutup Dairesini birbirine kattı. Şimdi de devasa bir deprem olurken şehri ziyaret etme zamanı. Yarış sırasında, makineli tüfekle ateş açılmasından roket saldırıları ve depremlere kadar uzanan yüzlerce sarsıcı, gerç
                                //        ]]>
                                //        <![CDATA[
                                //        ek zamanlı ve görkemli yıkım efektinin arasından sağ çıkmayı başarın. Süper arabalar, güç arabaları, süper motosikletler, chopper'lar ve bu efsanevi klasiklere yeni eklenen araçlardan oluşan 13 sınıf arasından aracınızı seçin. 4 oyuncu için bölünmüş ekran olanağı ve 1
                                //        ]]>
                                //        <![CDATA[
                                //        6 oyuncuya kadar oynama şansı ile kaosu internete taşıyın ve PlayStation Store'un yeni özelleştirilebilir araçlar, parçalar ve grafikleri içeren zengin indirilebilir içerik avantajlarından faydalanın. 3D'yi destekleyen TV'nizde muhteşem Stereoscopic 3D görüntülerle tüm yarış, çarpışma ve patlamaları yanı başınızda hissedin.
                                //        ]]>
                                //        </Details>


                                //        <Brand>STARCOM</Brand>
                                //        <ParentCategory>Elektronik</ParentCategory>
                                //        <Category>Ses ve Görüntü Sis.</Category>
                                //        <SubCategory>MP4 Player</SubCategory>
                                //        <Stock>Bol Stok</Stock>
                                //        <Barcode>0711719154280</Barcode>

                                //    </Product> 

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                ProcessedProductCode = product.ProductNo;

                                string parent = product.ParentCategory;
                                string category = product.Category;
                                string subCategory = product.SubCategory;
                                string attribute = product.Attribute;
                                string addition = product.CategoryAddition;
                                string groupname = (string.IsNullOrEmpty(parent) ? "" : parent) + (string.IsNullOrEmpty(category) ? "" : "-" + category) + (string.IsNullOrEmpty(subCategory) ? "" : "-" + subCategory) + (string.IsNullOrEmpty(attribute) ? "" : "-" + attribute) + (string.IsNullOrEmpty(addition) ? "" : "-" + addition);
                                string brand = product.Brand;

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(subCategory);
                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlIdForProductId, groupname, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlIdForProductId, groupname, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion
                                //test
                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);
                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                string ProductId = ProcessedProductCode;
                                string ProductName = product.ProductName;
                                decimal Price = Convert.ToDecimal(product.Price);
                                string Currency = ChangeExchangeCode(product.Currency);
                                decimal BuyingPrice = 0;
                                string Tax = product.Tax.Replace("%", "");
                                string ImageUrl = product.Image;
                                string Description = product.Details;
                                string Barcode = product.Barcode;

                                Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                bool FastCargo = false;
                                short DeliveryTime = xml.DeliveryTime;
                                decimal Amount = xml.Amount;
                                string AmountStr = product.Stock;
                                switch (AmountStr)
                                {
                                    case "Stokta Yok": Amount = 0; break;
                                    case "Tükenmek üzere": Amount = 1; break;
                                    case "Kritik Stok": Amount = 6; break;
                                    case "Stokta Var": Amount = 16; break;
                                    case "Bol Stok": Amount = 50; break;
                                    default: Amount = 0; break;
                                }

                                bool FirsatUrunu = false;
                                decimal IndirimliGosterim = 0;
                                if (addition == "Kampanya")
                                {
                                    FirsatUrunu = true;
                                    IndirimliGosterim = 15;
                                }

                                decimal AmountOnRoad = xml.AmountOnRoad;
                                if (Amount == 0)
                                {
                                    FastCargo = false;
                                }

                                decimal Desi = 0;
                                if (xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }


                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }

                                bool NewProduct = false;

                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    productId = dbProduct.Insert4(xml.XmlIdForProductId, ProductId, ProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, FirsatUrunu, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad, IndirimliGosterim);
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName4(xml.XmlIdForProductId, ProductId, ProductId, Barcode, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, FirsatUrunu, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad, IndirimliGosterim);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert4(xml.XmlIdForProductId, ProductId, ProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, FirsatUrunu, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad, IndirimliGosterim);
                                    }
                                }

                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0 && !string.IsNullOrEmpty(ImageUrl))
                                    {
                                        try
                                        {
                                            DownloadImage(productId, ImageUrl, 1);
                                        }
                                        catch
                                        {
                                            Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                            sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                        }
                                    }

                                    #endregion
                                }

                                if (productId > 0)
                                {
                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("YY") && (xml.Description.ToUpperInvariant().Contains("İTHALAT") || xml.Description.ToUpperInvariant().Contains("ITHALAT")))
                        {
                            #region YY İTHALAT

                            List<XElement> productList = xDoc.Descendants("products").Descendants("product").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {

                                #region tedarik kurtar
                                //lazım olanlar: ok KRTID, ok XMLID, ok XMLKARTID, ok XMLKARTKOD, ok XMLKARTBARKOD, ok ALISFIYATI, ok STOKMIKTAR, ok STOKMIKTARYOLDA, ok GUNCELLE
                                //string PName = XEResultString(product, "name");
                                //int pId = dbProduct.GetProductIdByProductName(PName);
                                //if (pId > 0)
                                //{
                                //    string xpId = XEResultString(product, "stockCode");
                                //    decimal xBuyingPrice = 0;
                                //    decimal xAmount = XEResultDecimal(product, "stock", xml.DecimalPoint);
                                //    decimal xAmountOnRoad = 0;

                                //    int xxProId = dbProduct.insertStokKartSaticiByName(pId, xml.XmlId, xpId, xpId, xpId, xBuyingPrice, xAmount, xAmountOnRoad, 1);
                                //    olanlar++;
                                //    if(olanlar==425){
                                //        olanlar = olanlar+0;
                                //    }
                                //}
                                //else
                                //{
                                //    olmayanlar++;
                                //}
                                //continue;

                                #endregion

                                #region Sample XML
                                /*<products>
                                        <product>
                                        <stockCode>9</stockCode>
                                        <parentCategory/>
                                        <category>ELEKTRONİK</category>
                                        <subCategory/>
                                        <brand>YY İthalat</brand>
                                        <name>UZAKTAN KUMANDALI PRİZ</name>
                                        <stock>0</stock>
                                        <desi>-</desi>
                                        <guarantee>-</guarantee>
                                        <cur>TL</cur>
                                        <buyingPrice>-</buyingPrice>
                                        <price>12.50</price>
                                        <tax>18</tax>
                                        <picture1>
                                        http://www.yyithalat.com/static/img/products_promo/uzaktan_kumandali_priz.jpg
                                        </picture1>
                                        <picture2>
                                        http://www.yyithalat.com/static/img/product_images_b/handy2.jpg
                                        </picture2>
                                        <picture3>
                                        http://www.yyithalat.com/static/img/product_images_b/handy3.jpg
                                        </picture3>
                                        <picture4>
                                        http://www.yyithalat.com/static/img/product_images_b/handy1.jpg
                                        </picture4>
                                        <details>
                                        <p>- Anında fişe takıp kullanabilirsiniz - Toplam 300W a kadar istediğiniz sayıda cihazı bağlayabilirsiniz - Kumanda 1 adet 6V kalem pil ile aynı bir tv kumandası gibi 1 yıl boyunca &ccedil;alışır.(Pil cihazla &uuml;cretsiz g&ouml;nderilir) - Kumanda radyo frekanslıdır, bu y&uuml;zden priz ile kumandanın birbirini g&ouml;rmesi gerekmez - 20mt mesafeye kadar kumanda etkilidir</p>
                                        </details>
                                        </product>
                                */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                int categoryID = XEResultInt(product, "category_id");
                                string groupname = XEResultString(product, "category");
                                string groupname2 = categoryID.ToString() + '-' + groupname;
                                string brand = XEResultString(product, "brand");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                ProcessedProductCode = XEResultString(product, "stockCode");
                                string ProductId = ProcessedProductCode;
                                string ProductName = XEResultString(product, "name");
                                /* Kdv li fiyat geliyor */
                                decimal Price = XEResultDecimal(product, "price", xml.DecimalPoint);
                                decimal BuyingPrice = 0;
                                string Currency = ChangeExchangeCode(XEResultString(product, "cur"));
                                decimal Tax = XEResultDecimal(product, "tax", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "stock", xml.DecimalPoint);
                                decimal AmountOnRoad = 0;
                                string ImageUrl = XEResultString(product, "picture1");
                                string ImageUrl2 = XEResultString(product, "picture2");
                                string ImageUrl3 = XEResultString(product, "picture3");
                                string ImageUrl4 = XEResultString(product, "picture4");
                                string ImageUrl5 = XEResultString(product, "picture5");
                                string Description = HttpUtility.HtmlDecode(XEResultString(product, "details"));

                                /* Kdv siz hale getiriliyor */
                                Price = Price / (1 + (Tax / 100));

                                Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                short DeliveryTime = xml.DeliveryTime;
                                decimal Desi;
                                if (xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }
                                decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                bool FastCargo = false;

                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }


                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }
                                bool NewProduct = false;
                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductId, ProductId, ProductName, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductId, ProductId, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductId, ProductId, ProductName, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                }
                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0)
                                    {
                                        short resimNo = 1;
                                        if (!string.IsNullOrEmpty(ImageUrl))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl2))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl2, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2);
                                            }
                                        }


                                        if (!string.IsNullOrEmpty(ImageUrl3))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl3, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl4))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl4, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl4, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl4);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl5))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl5, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl5, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl5);
                                            }
                                        }
                                    }

                                    #endregion
                                }

                                if (productId > 0)
                                {
                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("TOPTANCINIZ") || xml.Description.ToUpperInvariant().Contains("TOPTANCıNıZ") || xml.Description.ToUpperInvariant().Contains("TOPTANCiNiZ") || xml.Description.ToUpperInvariant().Contains("TOPTANCİNİZ"))
                        {
                            #region TOPTANCINIZ

                            List<XElement> productList = xDoc.Descendants("xml").Descendants("product").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {

                                #region Sample XML
                                /*<xml>
                                  <product>
                                    <media_gallery>
                                      <image1>http://www.toptanciniz.com/media/catalog/product/p/r/productimage-picture-dilek-feneri-dilek-balonu-3-adet-1107jpg.jpg</image1>
                                      <image2>http://www.toptanciniz.com/media/catalog/product/p/r/productimage-picture-dilek-feneri-dilek-balonu-3-adet-1109jpg.jpg</image2>
                                      <image3>http://www.toptanciniz.com/media/catalog/product/p/r/productimage-picture-dilek-feneri-dilek-balonu-3-adet-1108jpg.jpg</image3>
                                    </media_gallery>
                                    <categories>
                                      <category1>TV Ürünleri</category1>
                                    </categories>
                                    <name>Dilek Feneri Dilek Balonu 3 Adet</name>
                                    <sku>TV.00308.00</sku>
                                    <status>Aktif</status>
                                    <description>
                                      LOREM IPSUM DOLOR SIT AMET
                                    </description>
                                    <special_price>4.9000</special_price>
                                    <price>19.9000</price>
                                    <tax>18</tax>
                                    <image2>http://www.toptanciniz.com/media/catalog/product/p/r/productimage-picture-dilek-feneri-dilek-balonu-3-adet-1108jpg.jpg</image2>
                                    <image1>http://www.toptanciniz.com/media/catalog/product/p/r/productimage-picture-dilek-feneri-dilek-balonu-3-adet-1109jpg.jpg</image1>
                                    <image3>http://www.toptanciniz.com/media/catalog/product/p/r/productimage-picture-dilek-feneri-dilek-balonu-3-adet-1107jpg.jpg</image3>
                                    <quantity>329</quantity>
                                  </product>
                                </xml>*/
                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                ProcessedProductCode = XEResultString(product, "sku");
                                Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                int kategoriSayisi = product.Descendants("categories").Elements().Count();

                                //int categoryID = XEResultInt(product, "category_id");
                                string groupname = ""; //XEResultString(product, "category1");
                                if (kategoriSayisi >= 1)
                                {
                                    for (var ct = 1; ct <= kategoriSayisi; ct++)
                                    {
                                        var gnaddd = "category" + ct.ToString();
                                        groupname += XEResultString(product, gnaddd);
                                        //groupname += product.Descendants("categories").Descendants("category" + ct.ToString());
                                        if (ct < kategoriSayisi)
                                        {
                                            groupname += " - ";
                                        }
                                    }
                                }
                                string groupname2 = groupname;
                                string brand = "Toptanciniz";

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                //ProcessedProductCode = XEResultString(product, "sku");
                                string ProductId = ProcessedProductCode;
                                string ProductName = XEResultString(product, "name");
                                /* Kdv li fiyat geliyor */
                                decimal Price = XEResultDecimal(product, "special_price", xml.DecimalPoint);
                                decimal BuyingPrice = 0;
                                string Currency = "TL";
                                decimal Tax = XEResultDecimal(product, "tax", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "quantity", xml.DecimalPoint);
                                decimal AmountOnRoad = 0;




                                string ImageUrl = XEResultString(product, "image1");
                                string ImageUrl2 = XEResultString(product, "image2");
                                string ImageUrl3 = XEResultString(product, "image3");
                                string ImageUrl4 = XEResultString(product, "image4");
                                string ImageUrl5 = XEResultString(product, "image5");
                                string Description = HttpUtility.HtmlDecode(XEResultString(product, "description"));

                                /* Kdv siz hale getiriliyor */
                                Price = Price / (1 + (Tax / 100));

                                Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                short DeliveryTime = xml.DeliveryTime;
                                decimal Desi;
                                if (xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }
                                decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                bool FastCargo = false;

                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }


                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }
                                bool NewProduct = false;
                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductId, ProductId, ProductName, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductId, ProductId, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductId, ProductId, ProductName, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                }
                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0)
                                    {
                                        short resimNo = 1;
                                        if (!string.IsNullOrEmpty(ImageUrl))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl2))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl2, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2);
                                            }
                                        }


                                        if (!string.IsNullOrEmpty(ImageUrl3))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl3, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl4))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl4, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl4, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl4);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl5))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl5, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl5, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl5);
                                            }
                                        }
                                    }

                                    #endregion
                                }

                                if (productId > 0)
                                {
                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("BEBE") && (xml.Description.ToUpperInvariant().Contains("VİTRİN") || xml.Description.ToUpperInvariant().Contains("VITRIN")))
                        {
                            #region BEBE VİTRİNİ

                            List<XElement> productList = xDoc.Descendants("urunler").Descendants("urun").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {

                                #region tedarik kurtar
                                //lazım olanlar: ok KRTID, ok XMLID, ok XMLKARTID, ok XMLKARTKOD, ok XMLKARTBARKOD, ok ALISFIYATI, ok STOKMIKTAR, ok STOKMIKTARYOLDA, ok GUNCELLE
                                //string PName = XEResultString(product, "urun_adi");
                                //int pId = dbProduct.GetProductIdByProductName(PName);
                                //if (pId > 0)
                                //{
                                //    string xpId = XEResultString(product, "urun_id");
                                //    decimal xBuyingPrice = 0;
                                //    decimal xAmount = XEResultDecimal(product, "stok_adedi", xml.DecimalPoint);
                                //    decimal xAmountOnRoad = 0;

                                //    int xxProId = dbProduct.insertStokKartSaticiByName(pId, xml.XmlId, xpId, xpId, xpId, xBuyingPrice, xAmount, xAmountOnRoad, 1);
                                //    olanlar++;
                                //}
                                //else
                                //{
                                //    olmayanlar++;
                                //}
                                //continue;

                                #endregion

                                #region Sample XML OLD
                                /*<urunler>
                                     <urun>
                                      <urun_id>428</urun_id>
                                      <stok_kodu><![CDATA[SBDFJN23]]></stok_kodu>
                                      <urun_adi><![CDATA[Puset ve Oto Koltuğu Minderi]]></urun_adi>
                                      <marka_adi><![CDATA[SEVİ BEBE]]></marka_adi>
                                      <kategori_adi><![CDATA[Bebek Taşıma Ürünleri]]></kategori_adi>
                                      <kategori_id>487</kategori_id>
                                      <altkategori_adi><![CDATA[]]></altkategori_adi>
                                      <altkategori_id/>
                                      <piyasa_fiyati><![CDATA[]]></piyasa_fiyati>
                                      <fiyat>19.067</fiyat>
                                      <kdv_orani>18</kdv_orani>
                                      <para_birimi>TL</para_birimi>
                                      <stok_adedi>5</stok_adedi>
                                 * 
                                      <garanti_suresi>0</garanti_suresi>
                                      <resim_url><![CDATA[http://www.bebevitrini.com/modules/catalog/products/pr_01_428_max.jpg]]></resim_url>
                                      <details><![CDATA[Özellikler: Yumuşak yapısıyla bebeklere rahat bir seyahat sağlar Pamuklu kumaştandır, terletmez. Yastığı sayesinde bebeğin başı sağa sola kaymayacaktır. Yıkanabilir. Hem bebek arabanız için Hemde Oto koltuğunuz içindir.]]></details>
                                      <urun_url><![CDATA[http://www.bebevitrini.com/Puset-ve-Oto-Koltugu-Minderi,PR-428.html]]></urun_url>
                                      <indirimli_fiyat>18.49</indirimli_fiyat>
                                      <fiyat_eft_havale>17.57</fiyat_eft_havale>
                                     </urun>
                                */

                                #endregion

                                #region Sample XML NEW
                                //<urunler>
                                //     <urun>
                                //          <urun_id>428</urun_id>
                                //          <stok_kodu><![CDATA[SBDFJN23]]></stok_kodu>
                                //          <urun_adi><![CDATA[Puset ve Oto Koltuğu Minderi]]></urun_adi>
                                //          <marka_adi><![CDATA[SEVİ BEBE]]></marka_adi>
                                //          <kategori_adi><![CDATA[Bebek Taşıma Ürünleri]]></kategori_adi>
                                //          <kategori_id>487</kategori_id>
                                //          <altkategori_adi><![CDATA[]]></altkategori_adi>
                                //          <altkategori_id/>
                                //          <subCategory><![CDATA[]]></subCategory>
                                //          <subCategoryId/>
                                //          <isOptionedProduct>0</isOptionedProduct>
                                //          <isOptionOfAProduct>0</isOptionOfAProduct>
                                //          <rootProductId>0</rootProductId>
                                //          <rootProductStockCode><![CDATA[0]]></rootProductStockCode>
                                //          <piyasa_fiyati><![CDATA[]]></piyasa_fiyati>
                                //          <fiyat>19.067</fiyat>
                                //          <kdv_orani>18</kdv_orani>
                                //          <stok_adedi>5</stok_adedi>
                                //          <garanti_suresi>0</garanti_suresi>
                                //          <resim_url><![CDATA[http://www.bebevitrini.com/modules/catalog/products/pr_01_428_max.jpg]]></resim_url>
                                //          <picture2Path><![CDATA[]]></picture2Path>
                                //          <picture3Path><![CDATA[]]></picture3Path>
                                //          <dm3>5.00</dm3>
                                //          <details><![CDATA[Özellikler: Yumuşak yapısıyla bebeklere rahat bir seyahat sağlar Pamuklu kumaştandır, terletmez. Yastığı sayesinde bebeğin başı sağa sola kaymayacaktır. Yıkanabilir. Hem bebek arabanız için Hemde Oto koltuğunuz içindir.]]></details>
                                //          <categoryTree><![CDATA[Bebek Taşıma Ürünleri]]></categoryTree>
                                //          <productCategoryId>487</productCategoryId>
                                //          <productCategoryLabel><![CDATA[Bebek Taşıma Ürünleri]]></productCategoryLabel>
                                //          <indirimli_fiyat>18.49</indirimli_fiyat>
                                //          <title><![CDATA[Bebek Aksesurları]]></title>
                                //          <keywords><![CDATA[Sevi bebe Puset ve oto koltuğu minderi, oto koltuğu minderi]]></keywords>
                                //          <description><![CDATA[]]></description>
                                //    </urun>
                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                int isOptionOfAProduct = XEResultInt(product, "isOptionOfAProduct");
                                if (isOptionOfAProduct == 1)
                                {
                                    continue;
                                }

                                int categoryID = XEResultInt(product, "kategori_id");
                                string groupname = XEResultString(product, "kategori_adi");
                                int altcategoryID = XEResultInt(product, "altkategori_id");
                                string altgroupname = XEResultString(product, "altkategori_adi");
                                int subCategoryId = XEResultInt(product, "subCategoryId");
                                string subCategory = XEResultString(product, "subCategory");

                                string groupname2 = groupname;

                                if (!string.IsNullOrEmpty(subCategory))
                                {
                                    groupname2 = altgroupname + "-" + subCategory;
                                    groupname = subCategory;
                                }
                                else if (!string.IsNullOrEmpty(altgroupname))
                                {
                                    groupname2 = groupname + "-" + altgroupname;
                                    groupname = altgroupname;
                                }

                                string brand = XEResultString(product, "marka_adi");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                ProcessedProductCode = XEResultString(product, "urun_id");
                                string ProductId = ProcessedProductCode;
                                string ProductCode = XEResultString(product, "stok_kodu");
                                string ProductName = XEResultString(product, "urun_adi");
                                decimal Price = XEResultDecimal(product, "indirimli_fiyat", xml.DecimalPoint);
                                decimal BuyingPrice = 0;
                                decimal PriceWithoutDiscount = XEResultDecimal(product, "fiyat", xml.DecimalPoint);
                                string Currency = ChangeExchangeCode("TL"); // XEResultString(product, "para_birimi");
                                decimal Tax = XEResultDecimal(product, "kdv_orani", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "stok_adedi", xml.DecimalPoint);
                                decimal AmountOnRoad = 0;

                                string ImageUrl = XEResultString(product, "resim_url");
                                string ImageUrl2 = XEResultString(product, "picture2Path");
                                string ImageUrl3 = XEResultString(product, "picture3Path");

                                string Description = HttpUtility.HtmlDecode(XEResultString(product, "details"));

                                short WarantyTime = (short)XEResultInt(product, "garanti_suresi");
                                string WarantyPeriod = "";
                                if (WarantyTime > 0)
                                {
                                    WarantyPeriod = "Ay";
                                }

                                if (Price == 0)
                                {
                                    Price = PriceWithoutDiscount;
                                }

                                Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                short DeliveryTime = xml.DeliveryTime;
                                decimal Desi;
                                if (xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }

                                decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                bool FastCargo = false;
                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }


                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }

                                bool NewProduct = false;

                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    //Logger.Write("XML Import Product Insert : " + ProductId + " - " + ProductName, "Trace");
                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, WarantyTime, WarantyPeriod, "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);

                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    //Logger.Write("XML Import Product Updated : " + ProductId + " - " + ProductName, "Trace");
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, WarantyTime, WarantyPeriod, "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName, category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                              Description, xml.ReloadDescription, false, WarantyTime, WarantyPeriod, "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                    //                                  #warning daha sonra kaldırılacak
                                    //                                  Logger.Write("XML Import Product Group Inserted : " + productId.ToString() + "," + category2.CategoryId.ToString() + ",A", "Trace");
                                    //                                  dbProduct.InsertGroup(productId, category2.CategoryId, "A");
                                    //                                  Logger.Write("XML Import Product Group Inserted : " + productId.ToString() + "," + brandGroup.CategoryId + ",M", "Trace");
                                    //                                  dbProduct.InsertGroup(productId, brandGroup.CategoryId, "M");
                                }

                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0)
                                    {
                                        short resimNo = 1;
                                        if (!string.IsNullOrEmpty(ImageUrl))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl2))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl2, resimNo);
                                                resimNo++;
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2);
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(ImageUrl3))
                                        {
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl3, resimNo);
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3);
                                            }
                                        }
                                    }

                                    #endregion
                                }

                                if (productId > 0)
                                {
                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("BAREM"))
                        {
                            #region BAREM

                            List<XElement> productList = xDoc.Descendants("BAREM").Descendants("urunler").Descendants("urun").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {

                                #region tedarik kurtar
                                ////lazım olanlar: ok KRTID, ok XMLID, ok XMLKARTID, ok XMLKARTKOD, ok XMLKARTBARKOD, ok ALISFIYATI, ok STOKMIKTAR, ok STOKMIKTARYOLDA, ok GUNCELLE
                                //string PName = XEResultString(product, "ad");

                                //int pId = dbProduct.GetProductIdByProductName(PName);
                                //if (pId > 0)
                                //{
                                //    string xpId = XEResultString(product, "kod");
                                //    decimal xBuyingPrice = XEResultDecimal(product, "bayifiyati", xml.DecimalPoint);
                                //    decimal xAmount = xml.Amount;
                                //    decimal xAmountOnRoad = xml.AmountOnRoad;

                                //    int xxProId = dbProduct.insertStokKartSaticiByName(pId, xml.XmlId, xpId, xpId, xpId, xBuyingPrice, xAmount, xAmountOnRoad, 1);
                                //    olanlar++;
                                //    if (olanlar == 425)
                                //    {
                                //        olanlar = olanlar + 0;
                                //    }
                                //}
                                //else if (pId == -1)
                                //{
                                //    zatenolanlar++;
                                //}
                                //else
                                //{
                                //    olmayanlar++;
                                //}
                                //urunsayisi++;
                                //if (urunsayisi == productList.Count() - 2)
                                //{
                                //    var z = 1;
                                //}

                                //continue;

                                #endregion

                                #region Sample XML
                                /*
                                  <BAREM>
                                    <urunler>
                                        <urun>
                                            <kod>AA SG TN PNEW3006</kod>
                                            <marka>PANASONIC</marka>
                                            <ad>PANASONIC BİLEKTEN KAN BASINCI(TANSİYON)ÖLÇER,ELEK</ad>
                                            <kdv>8</kdv>
                                            <pb>TL</pb>
                                 
                                            <kategoriler>
                                                <kategori>
                                                    <katkod>95000</katkod>
                                                    <aciklama>SAĞLIK ÜRÜNLERİ</aciklama>
                                                </kategori>
                                                <kategori>
                                                    <katkod>95000 150</katkod>
                                                    <aciklama>SAĞLIK ÜRÜNLERİ</aciklama>
                                                </kategori>
                                            </kategoriler>
                                            <teskf>87.89</teskf>
                                            <bayifiyati>70.31</bayifiyati>
                                            <ozelfiyati>68.20</ozelfiyati>
                                            <ozelfiyatipb>TL</ozelfiyatipb>
                                            <stok>var</stok>
                                 
                                 
                                            <KTA_EKART00_U_BARKOD/>
                                 
                                            <birim>ADET</birim>
                                            <ps>
                                                <s>
                                                    <quest>Model</quest>
                                                    <val><![CDATA[ EW-3006 Tansiyon Aleti ]]></val>
                                                </s>
                                                <s>
                                                    <quest>Teknik Özellikler 1</quest>
                                                    <val><![CDATA[&lt;li&gt;Tip Akıllı PANASONIC FUZZY LOGIC Teknolojili osilometrik ölçüm &lt;li&gt;Veri ölçümü Sistolik ve diastolik kan basıncı ve nabız &lt;li&gt;Hassasiyet Kan basıncı: +/- 3 mmHg, Nabız oranı: +/- % 5 &lt;li&gt;Kontrast ekran Gri &lt;li&gt;Rakam boyutu [mm] 10.5]]></val>
                                                </s>
                                                <s>
                                                    <quest>Teknik Özellikler 2</quest>
                                                    <val><![CDATA[&lt;li&gt;Şişirme/Tahliye sistemi Şişirme ve hızlı tahliye esnasında otomatik ölçüm &lt;li&gt;Bellek 90 &lt;li&gt;Yüksek kan basıncı uyarısı Yanıp söner rakam &lt;li&gt;Bileklik ölçüsü [cm]'den 12.5 [cm]'ye 22.0 &lt;li&gt;Otomatik kapanma Ölçümden yaklaşık 5 dk. Sonra]]></val>
                                                </s>
                                                <s>
                                                    <quest>Teknik Özellikler 3</quest>
                                                    <val><![CDATA[&lt;li&gt;Güç Kaynağı 2 x 1,5 V Alkalin (2 x LR03/ AAA/ Mikro) &lt;li&gt;Renk Beyaz &lt;li&gt;Ağırlık 104 g (pilsiz)]]></val>
                                                </s>
                                                <s>
                                                    <quest>Teknik Özellikler 4</quest>
                                                    <val><![CDATA[&lt;li&gt;Kaynak rehber 21.28.01.3022 &lt;li&gt;Standart Aksesuarlar Konumlama asistanlı seyahat kılıfı]]></val>
                                                </s>
                                                <s>
                                                    <quest>Garanti</quest>
                                                    <val><![CDATA[ 2 yıl ]]></val>
                                                </s>
                                            </ps>
                                            <resimler>
                                                <resim>http://www.baremnet.com.tr/ProductImages/PNEW3006_k.jpg</resim>
                                                <resim>http://www.baremnet.com.tr/ProductImages/PNEW3006_o.jpg</resim>
                                                <resim>http://www.baremnet.com.tr/ProductImages/PNEW3006_b.jpg</resim>
                                            </resimler>
                                        </urun>

                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                ProcessedProductCode = XEResultString(product, "kod");
                                Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                List<XElement> kategoriList = product.Descendants("kategoriler").Descendants("kategori").ToList();
                                if (kategoriList == null || kategoriList.Count() == 0)
                                {
                                    Logger.Write("Kategori bilgisi bulunamadı! : " + ProcessedProductCode, "Exception");
                                    sbReport.Append("Kategori bilgisi bulunamadı! : " + ProcessedProductCode);
                                    continue;
                                }

                                string categoryID = XEResultString(kategoriList[kategoriList.Count() - 1], "katkod");
                                string groupname = XEResultString(kategoriList[kategoriList.Count() - 1], "aciklama");
                                string groupname2 = categoryID.ToString() + '-' + groupname;
                                string brand = XEResultString(product, "marka");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                string ProductCode = ProcessedProductCode;
                                string ProductId = ProductCode;
                                string ProductName = XEResultString(product, "ad");
                                decimal Tax = XEResultDecimal(product, "kdv", xml.DecimalPoint);
                                string Currency = ChangeExchangeCode(XEResultString(product, "pb"));
                                string CurrencyOzel = ChangeExchangeCode(XEResultString(product, "ozelfiyatipb"));
                                decimal Price = XEResultDecimal(product, "teskf", xml.DecimalPoint);
                                decimal BuyingPrice = XEResultDecimal(product, "bayifiyati", xml.DecimalPoint);
                                decimal OzelFiyat = XEResultDecimal(product, "ozelfiyati", xml.DecimalPoint);
                                string Stok = XEResultString(product, "stok");
                                string Model = "";
                                string Description = "";
                                string WarantyPeriod = "Yıl";
                                int WarantyTime = 0;
                                string DeliveryPeriod = "Gün";
                                int DeliveryTime = 0;
                                decimal CargoPriceField = 0;
                                decimal CargoPriceAdditionField = 0;
                                bool FreeCargo = false;
                                bool FastCargo = false;
                                bool NewProduct = false;
                                decimal Desi = 0;
                                if (string.IsNullOrEmpty(Convert.ToString(xmlImportGroup2.Desi)) || xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }
                                decimal Weight = 0;
                                decimal Width = 0;
                                decimal Length = 0;
                                decimal Height = 0;

                                decimal Amount = 0;
                                decimal AmountOnRoad = 0;

                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }


                                if (string.IsNullOrEmpty(CurrencyOzel))
                                {
                                    CurrencyOzel = Currency;
                                }

                                if (OzelFiyat > 0)
                                {
                                    BuyingPrice = OzelFiyat;
                                    Currency = CurrencyOzel;
                                }

                                if (Currency != "TL")
                                {
                                    decimal rate = GetRate(ExchangeRates, TCMBExchangeRates, Currency);
                                    BuyingPrice = Math.Round(BuyingPrice * rate, 2);
                                    Currency = "TL";
                                }

                                Price = Math.Round(BuyingPrice * xmlBrand.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                if (Stok.ToLowerInvariant() == "var")
                                {
                                    Amount = xml.Amount;
                                    AmountOnRoad = 0;
                                }

                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }

                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    //Logger.Write("Product Insert : " + ProductId + " - " + ProductName, "Trace");
                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                  category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);

                                    //Logger.Write("Product Inserted : ProductId => " + productId.ToString(), "Trace");
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    //Logger.Write("Product Update : " + productId.ToString() + " " + ProductId + " - " + ProductName, "Trace");
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode,
                                                                  category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                  category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    //Logger.Write("Product Updated : ProductId => " + productId.ToString(), "Trace");
                                }
                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0)
                                    {
                                        List<XElement> resimList = product.Descendants("resimler").Descendants("resim").ToList();
                                        if (resimList != null && resimList.Count() > 0)
                                        {
                                            string ImageUrl = resimList[resimList.Count() - 1].Value;
                                            if (!string.IsNullOrEmpty(ImageUrl))
                                            {
                                                Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                                try
                                                {
                                                    DownloadImage(productId, ImageUrl, 1);
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                                }
                                            }
                                            else
                                            {
                                                Logger.Write("XML Import Product Image Info Not Found: ProductId => " + productId.ToString(), "Exception");
                                                sb.Append("XML Import Product Image Info Not Found: ProductId => " + productId.ToString());
                                            }
                                        }
                                        else
                                        {
                                            Logger.Write("XML Import Product Image Info Not Found: ProductId => " + productId.ToString(), "Exception");
                                            sb.Append("XML Import Product Image Info Not Found: ProductId => " + productId.ToString());
                                        }
                                    }

                                    #endregion
                                }


                                if (productId > 0)
                                {
                                    #region Stok Kart Ekstra Alanlar

                                    foreach (var productinfo in product.Descendants("ps").Descendants("s"))
                                    {
                                        string type = HttpUtility.HtmlDecode(XEResultString(productinfo, "quest"));
                                        string Information = HttpUtility.HtmlDecode(XEResultString(productinfo, "val"));

                                        dbProductInfo.Insert(productId, type, Information);
                                    }

                                    #endregion

                                    #region Stok Kart Ekstra Gruplar

                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }

                                    #endregion
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("APEX"))
                        {
                            #region APEX
                            if (xml.Description.ToUpperInvariant().Contains("KATALOG"))
                            {
                                #region Katalog

                                List<XElement> productList = xDoc.Descendants("Urunler").Descendants("Urun").ToList();

                                Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                                dbProduct.ResetAmount(xml.XmlIdForProductId);
                                Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                                foreach (var product in productList)
                                {

                                    #region Sample XML
                                    /*
                                      <Urunler>
                                          <Urun>
                                            <StokKodu>8697911015555</StokKodu>
                                            <UrunAdi>Extra Halı  80 X 120 Alya</UrunAdi>
                                            <UrunMarka>Apex</UrunMarka>
                                            <UrunKategori>Kaymaz Taban Halılar</UrunKategori>
                                            <UrunGrubu>Extra Halı</UrunGrubu>
                                            <UrunRenk>Alya</UrunRenk>
                                            <UrunEbat>80x120</UrunEbat>
                                            <UrunVaryantID>01311</UrunVaryantID>
                                            <UrunAdet>90,00</UrunAdet>
                                            <UrunKdv>8</UrunKdv>
                                            <UrunM2>0,96</UrunM2>
                                            <UrunM3>10,24</UrunM3>
                                            <UrunKg>2,03</UrunKg>
                                            <UrunDesi>3,41</UrunDesi>
                                            <UrunBarkod>8697911015555</UrunBarkod>
                                            <UrunToptanFiyat>48,00</UrunToptanFiyat>
                                            <UrunPrekendeFiyat>80,00</UrunPrekendeFiyat>
                                            <UrunParaBirimi>TL</UrunParaBirimi>
                                            <UrunResim1>Http://www.apexbayi.com/apex_resim/zoom/01311__103.jpg</UrunResim1>
                                            <UrunResim2>Http://www.apexbayi.com/apex_resim/zoom/01311__102.jpg</UrunResim2>
                                            <UrunResim3>Http://www.apexbayi.com/apex_resim/zoom/01311__100.jpg</UrunResim3>
                                            <UrunResim4>Http://www.apexbayi.com/apex_resim/zoom/01311__101.jpg</UrunResim4>
                                            <UrunResim5/>
                                            <UrunResim6/>
                                            <UrunResim7/>
                                            <UrunResim8/>
                                            <UrunResim9/>
                                            <UrunResim10/>
                                            <UrunKisaAciklama/>
                                            <UrunAciklama></UrunAciklama>
                                          </Urun>
                                      </Urunler>
                                    */

                                    #endregion

                                    #region Processed Product Count Log

                                    ProductCount++;
                                    if (ProductCount % 100 == 0)
                                    {
                                        Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                    }

                                    #endregion

                                    ProcessedProductCode = XEResultString(product, "StokKodu");
                                    Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                    //string categoryID = XEResultString(kategoriList[kategoriList.Count() - 1], "katkod");
                                    string groupname = XEResultString(product, "UrunKategori");
                                    string groupname2 = xml.XmlIdForProductId.ToString() + '-' + groupname;
                                    string brand = XEResultString(product, "UrunMarka");

                                    #region Category Group Control

                                    XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                    if (xmlImportGroup2 == null)
                                    {
                                        int altGrupId = dbCategory.GetByName(groupname);

                                        Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                        if (altGrupId > 0)
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                        }
                                        xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                        sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                    }
                                    Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                    if (!xmlImportGroup2.IsActive || category2 == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    #region Brand Control

                                    XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    if (xmlBrand == null)
                                    {
                                        int brandId = dbCategory.GetByName(brand);

                                        Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                        if (brandId > 0)
                                        {
                                            dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                            xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                            continue;
                                        }
                                        sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                    }
                                    Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                    if (!xmlBrand.IsActive || brandGroup == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    #region Vars

                                    string ProductCode = ProcessedProductCode;
                                    string ProductId = ProductCode;
                                    string ProductVariant = XEResultString(product, "UrunVaryantID");
                                    //string ProductName = XEResultString(product, "UrunAdi"); //apexhalı
                                    string ProductName = XEResultString(product, "UrunMarka") + " " + XEResultString(product, "UrunGrubu") + " " + XEResultString(product, "UrunRenk");
                                    string VariantValue = XEResultString(product, "UrunEbat");
                                    decimal Tax = XEResultDecimal(product, "UrunKdv", xml.DecimalPoint);
                                    string Currency = ChangeExchangeCode(XEResultString(product, "UrunParaBirimi"));

                                    decimal Price = XEResultDecimal(product, "UrunPrekendeFiyat", xml.DecimalPoint);
                                    decimal BuyingPrice = XEResultDecimal(product, "UrunToptanFiyat", xml.DecimalPoint);
                                    if (Parameters.SetPricesWithoutTax)
                                    {
                                        Price = Price * (1 + (Tax / 100));
                                        BuyingPrice = BuyingPrice * (1 + (Tax / 100));
                                    }
                                    string Stok = XEResultString(product, "UrunAdet");
                                    string Model = "";
                                    string Description = XEResultString(product, "UrunAciklama");
                                    Description = Description.Replace("images/products1/", "http://www.apexhali.com/images/products1/").Replace("rel=\"shadowbox[group]\"", "class=\"product-detail-image\"");
                                    string WarantyPeriod = "Yıl";
                                    int WarantyTime = 0;
                                    string DeliveryPeriod = "Gün";
                                    int DeliveryTime = 0;
                                    decimal CargoPriceField = 0;
                                    decimal CargoPriceAdditionField = 0;
                                    bool FreeCargo = false;
                                    bool FastCargo = false;
                                    bool NewProduct = false;
                                    decimal Desi = XEResultDecimal(product, "UrunDesi", xml.DecimalPoint);
                                    if (string.IsNullOrEmpty(Desi.ToString()) || Desi == 0)
                                    {
                                        if (!string.IsNullOrEmpty(Convert.ToString(xmlImportGroup2.Desi)) && xmlImportGroup2.Desi != 0)
                                        {
                                            Desi = xmlImportGroup2.Desi;
                                        }
                                        else
                                        {
                                            Desi = xml.Desi != 0 ? xml.Desi : 0;
                                        }
                                    }
                                    decimal Weight = XEResultDecimal(product, "UrunKg", xml.DecimalPoint);
                                    decimal Width = 0;
                                    decimal Length = 0;
                                    decimal Height = 0;

                                    decimal Amount = XEResultDecimal(product, "UrunAdet", xml.DecimalPoint);
                                    decimal AmountOnRoad = 0;

                                    if (Amount == 0)
                                    {
                                        Amount = xml.Amount;
                                        if (Amount == 0)
                                        {
                                            FastCargo = false;
                                        }
                                    }
                                    if (AmountOnRoad == 0)
                                    {
                                        AmountOnRoad = xml.AmountOnRoad;
                                    }


                                    if (Currency != "TL")
                                    {
                                        decimal rate = GetRate(ExchangeRates, TCMBExchangeRates, Currency);
                                        BuyingPrice = Math.Round(BuyingPrice * rate, 2);
                                        Currency = "TL";
                                    }

                                    Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                    if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                    {
                                        Price += xml.PriceToAdd;
                                    }
                                    if (xml.PriceToAddAll > 0)
                                    {
                                        Price += xml.PriceToAddAll;
                                    }

                                    if (Stok.ToLowerInvariant() == "var")
                                    {
                                        Amount = xml.Amount;
                                        AmountOnRoad = 0;
                                    }


                                    string UrunResim1 = XEResultString(product, "UrunResim1");
                                    string UrunResim2 = XEResultString(product, "UrunResim2");
                                    string UrunResim3 = XEResultString(product, "UrunResim3");
                                    string UrunResim4 = XEResultString(product, "UrunResim4");
                                    string UrunResim5 = XEResultString(product, "UrunResim5");

                                    #endregion

                                    int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                    if (productId == -2)
                                    {
                                        productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                        if (productId > 0)
                                        {
                                            dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                        }
                                        continue;
                                    }

                                    if (productId == -1 && xml.InsertNewProduct)
                                    {
                                        //Logger.Write("Product Insert : " + ProductId + " - " + ProductName, "Trace");
                                        productId = dbProduct.Insert3(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad, ProductVariant, VariantValue);

                                        //Logger.Write("Product Inserted : ProductId => " + productId.ToString(), "Trace");
                                        NewProduct = true;
                                        newProductCounter++;
                                    }
                                    else
                                    {
                                        //Logger.Write("Product Update : " + productId.ToString() + " " + ProductId + " - " + ProductName, "Trace");
                                        if (xml.StkNameNotUpdate)
                                        {
                                            productId = dbProduct.InsertWithoutProductNameAndVariant(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad, ProductVariant, VariantValue);
                                        }
                                        else
                                        {
                                            productId = dbProduct.Insert3(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad, ProductVariant, VariantValue);
                                        }
                                        //Logger.Write("Product Updated : ProductId => " + productId.ToString(), "Trace");
                                    }
                                    //ana ürünmü yoksa alt ürünmü belirleyelim
                                    int ustUrunId = dbProduct.GetVariantId(productId);


                                    if (NewProduct || xml.ReInstallProductImg)
                                    {
                                        #region New Product to Update Image

                                        if (productId > 0 && ustUrunId == 0)
                                        {
                                            short resimNo = 1;
                                            if (!string.IsNullOrEmpty(UrunResim1))
                                            {
                                                try
                                                {
                                                    DownloadImage(productId, UrunResim1, resimNo); //90, true
                                                    resimNo++;
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim1, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim1);
                                                }
                                            }
                                            if (!string.IsNullOrEmpty(UrunResim2))
                                            {
                                                try
                                                {
                                                    DownloadImage(productId, UrunResim2, resimNo);
                                                    resimNo++;
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim2, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim2);
                                                }
                                            }


                                            if (!string.IsNullOrEmpty(UrunResim3))
                                            {
                                                try
                                                {
                                                    DownloadImage(productId, UrunResim3, resimNo);
                                                    resimNo++;
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim3, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim3);
                                                }
                                            }
                                            if (!string.IsNullOrEmpty(UrunResim4))
                                            {
                                                try
                                                {
                                                    DownloadImage(productId, UrunResim4, resimNo);
                                                    resimNo++;
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim4, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim4);
                                                }
                                            }
                                            if (!string.IsNullOrEmpty(UrunResim5))
                                            {
                                                try
                                                {
                                                    DownloadImage(productId, UrunResim5, resimNo);
                                                    resimNo++;
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim5, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim5);
                                                }
                                            }
                                        }

                                        #endregion
                                    }


                                    if (productId > 0)
                                    {
                                        #region Stok Kart Ekstra Alanlar

                                        foreach (var productinfo in product.Descendants("ps").Descendants("s"))
                                        {
                                            string type = HttpUtility.HtmlDecode(XEResultString(productinfo, "quest"));
                                            string Information = HttpUtility.HtmlDecode(XEResultString(productinfo, "val"));

                                            dbProductInfo.Insert(productId, type, Information);
                                        }

                                        #endregion

                                        #region Stok Kart Ekstra Gruplar

                                        foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                        {
                                            dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                        }

                                        #endregion
                                    }

                                    if (Amount + AmountOnRoad <= 0)
                                    {
                                        dbProduct.SetInactiveByProductId(productId);
                                    }
                                    else
                                    {
                                        dbProduct.SetActiveByProductId(productId);
                                    }
                                }

                                dbProduct.SetInactive(xml.XmlIdForProductId);
                                Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                                #endregion
                            }
                            else if (xml.Description.ToUpperInvariant().Contains("OZEL") || xml.Description.ToUpperInvariant().Contains("ÖZEL"))
                            {
                                #region Özel Ürünler

                                var urunGrup = "";
                                var urunMarka = "Apex";
                                if (xml.Description.ToUpperInvariant().Contains("VINTAGE") || xml.Description.ToUpperInvariant().Contains("VİNTAGE"))
                                {
                                    urunGrup = "Vintage";
                                }
                                else if (xml.Description.ToUpperInvariant().Contains("KİLİM") || xml.Description.ToUpperInvariant().Contains("KILIM"))
                                {
                                    urunGrup = "Kilim";
                                }
                                else if (xml.Description.ToUpperInvariant().Contains("HERITAGE") || xml.Description.ToUpperInvariant().Contains("HERİTAGE"))
                                {
                                    urunGrup = "Heritage";
                                }
                                else if (xml.Description.ToUpperInvariant().Contains("PATCHWORK"))
                                {
                                    urunGrup = "Patchwork Kilim";
                                }
                                #region Process

                                List<XElement> productList = xDoc.Descendants("Products").Descendants("Product").ToList();

                                Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                                dbProduct.ResetAmount(xml.XmlIdForProductId);
                                Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                                foreach (var product in productList)
                                {

                                    #region Sample XML
                                    /*
                                      <Products>
                                          <Product>
                                            <ApexStockID>01KLMU160230G11</ApexStockID>
                                            <ApexSerialID>0111_160x230</ApexSerialID>
                                            <ApexWarehouseID>34</ApexWarehouseID>
                                            <ProductSerialID>0111</ProductSerialID>
                                            <ProductStock>1</ProductStock>
                                            <ProductHeight>160</ProductHeight>
                                            <ProductWidth>230</ProductWidth> 
                                            <ProductSize>069X123</ProductSize>
                                            <ProductSquareMeters>36.80</ProductSquareMeters>
                                            <ProductKg>2.42</ProductKg>
                                            <ProductDeci>1.49</ProductDeci>
                                            <ProductColor>Naturel</ProductColor>
                                            <ProductWholesalePrice>25730.56</ProductWholesalePrice>
                                            <ProductRetailPrice>54169.60</ProductRetailPrice>
                                            <ProductVAT>8</ProductVAT>
                                            <ProductCurrency>TL</ProductCurrency>
                                            <ProductThumbImage>http://www.apexbayi.com/apex_resim/kilim/thumb/0111_160x230.jpg</ProductThumbImage>
                                            <ProductZoomImage>http://www.apexbayi.com/apex_resim/kilim/0111_160x230.jpg</ProductZoomImage>
                                            <ProductDescTR>
                                                <![CDATA[ Geri dönüşümün en ihtişamlı hali.Mimaride ve tasarımda Mid-century olarak adlandırılan 60 ve 70 li yıllarda Anadolunun birçok
                                                yöresinde dokunan el halıları, yeni yüzleriyle tekrar hayat buluyor.Bu döneme ait binlerce halı arasında yapılan seçkide , tabiri caizse
                                                çil durumda olanları, bitkisel boyalarla boyanarak modern evlerde yerini almaya hazırlanıyor.Her model benzersizdir.]]> 
                                            </ProductDescTR>
                                          </Product>
                                      </Products>
                                    */

                                    #endregion

                                    #region Processed Product Count Log

                                    ProductCount++;
                                    if (ProductCount % 100 == 0)
                                    {
                                        Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                    }

                                    #endregion

                                    ProcessedProductCode = XEResultString(product, "ApexSerialID");
                                    Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                    //string categoryID = XEResultString(kategoriList[kategoriList.Count() - 1], "katkod");
                                    string groupname = urunGrup;
                                    string groupname2 = xml.XmlIdForProductId.ToString() + '-' + groupname;
                                    string brand = urunMarka;

                                    #region Category Group Control

                                    XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                    if (xmlImportGroup2 == null)
                                    {
                                        int altGrupId = dbCategory.GetByName(groupname);

                                        Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                        if (altGrupId > 0)
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                        }
                                        xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                        sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                    }
                                    Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                    if (!xmlImportGroup2.IsActive || category2 == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    #region Brand Control

                                    XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    if (xmlBrand == null)
                                    {
                                        int brandId = dbCategory.GetByName(brand);

                                        Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                        if (brandId > 0)
                                        {
                                            dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                            xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                        }
                                        else
                                        {
                                            dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                            continue;
                                        }
                                        sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                    }
                                    Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                    if (!xmlBrand.IsActive || brandGroup == null)
                                    {
                                        continue;
                                    }

                                    #endregion

                                    #region Vars

                                    string ProductCode = ProcessedProductCode;
                                    string ProductId = ProductCode;
                                    //string ProductName = XEResultString(product, "UrunAdi"); //apexhalı
                                    string ProductName = urunMarka + " " + urunGrup + " " + XEResultString(product, "ProductColor") + " " + XEResultString(product, "ProductSerialID") + " " + XEResultString(product, "ProductSize").ToLowerInvariant();
                                    decimal Tax = XEResultDecimal(product, "ProductVAT", xml.DecimalPoint);
                                    string Currency = ChangeExchangeCode(XEResultString(product, "ProductCurrency"));
                                    decimal Price = XEResultDecimal(product, "ProductRetailPrice", xml.DecimalPoint);
                                    decimal BuyingPrice = XEResultDecimal(product, "ProductWholesalePrice", xml.DecimalPoint);
                                    string Stok = XEResultString(product, "ProductStock");
                                    string Model = "";
                                    string Description = "";
                                    try
                                    {
                                        Description = XEResultString(product, "ProductDescTR") != null ? XEResultString(product, "ProductDescTR") : "";
                                    }
                                    catch { }
                                    string WarantyPeriod = "Yıl";
                                    int WarantyTime = 0;
                                    string DeliveryPeriod = "Gün";
                                    int DeliveryTime = 0;
                                    decimal CargoPriceField = 0;
                                    decimal CargoPriceAdditionField = 0;
                                    bool FreeCargo = false;
                                    bool FastCargo = false;
                                    bool NewProduct = false;
                                    decimal Desi = 0;
                                    try
                                    {
                                        Desi = !string.IsNullOrEmpty(XEResultString(product, "ProductDeci")) ? XEResultDecimal(product, "ProductDeci", xml.DecimalPoint) : 0;
                                    }
                                    catch { }
                                    if (string.IsNullOrEmpty(Desi.ToString()) || Desi == 0)
                                    {
                                        if (!string.IsNullOrEmpty(Convert.ToString(xmlImportGroup2.Desi)) && xmlImportGroup2.Desi != 0)
                                        {
                                            Desi = xmlImportGroup2.Desi;
                                        }
                                        else
                                        {
                                            Desi = xml.Desi != 0 ? xml.Desi : 0;
                                        }
                                    }
                                    decimal Weight = 0;
                                    try
                                    {
                                        Weight = !string.IsNullOrEmpty(XEResultString(product, "ProductKg")) ? XEResultDecimal(product, "ProductKg", xml.DecimalPoint) : 0;
                                    }
                                    catch { }

                                    decimal Width = XEResultDecimal(product, "ProductHeight", xml.DecimalPoint);
                                    decimal Length = XEResultDecimal(product, "ProductWidth", xml.DecimalPoint);
                                    decimal Height = 0.6m;

                                    decimal Amount = XEResultDecimal(product, "ProductStock", xml.DecimalPoint);
                                    decimal AmountOnRoad = 0;

                                    if (Amount == 0)
                                    {
                                        Amount = xml.Amount;
                                        if (Amount == 0)
                                        {
                                            FastCargo = false;
                                        }
                                    }
                                    if (AmountOnRoad == 0)
                                    {
                                        AmountOnRoad = xml.AmountOnRoad;
                                    }


                                    if (Currency != "TL")
                                    {
                                        decimal rate = GetRate(ExchangeRates, TCMBExchangeRates, Currency);
                                        BuyingPrice = Math.Round(BuyingPrice * rate, 2);
                                        Currency = "TL";
                                    }

                                    Price = Math.Round(Price * xmlBrand.ProfitRate, 2);

                                    if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                    {
                                        Price += xml.PriceToAdd;
                                    }
                                    if (xml.PriceToAddAll > 0)
                                    {
                                        Price += xml.PriceToAddAll;
                                    }

                                    if (Stok.ToLowerInvariant() == "var")
                                    {
                                        Amount = xml.Amount;
                                        AmountOnRoad = 0;
                                    }


                                    string UrunResim = XEResultString(product, "ProductZoomImage");

                                    #endregion

                                    int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                    if (productId == -2)
                                    {
                                        productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                        if (productId > 0)
                                        {
                                            dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                        }
                                        continue;
                                    }

                                    #region insert
                                    if (productId == -1 && xml.InsertNewProduct)
                                    {
                                        //Logger.Write("Product Insert : " + ProductId + " - " + ProductName, "Trace");
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad);

                                        //Logger.Write("Product Inserted : ProductId => " + productId.ToString(), "Trace");
                                        NewProduct = true;
                                        newProductCounter++;
                                    }
                                    else
                                    {
                                        //Logger.Write("Product Update : " + productId.ToString() + " " + ProductId + " - " + ProductName, "Trace");
                                        if (xml.StkNameNotUpdate)
                                        {
                                            productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad);
                                        }
                                        else
                                        {
                                            productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                      category2.CategoryId, brandGroup.CategoryId, Tax, "AD", Price, BuyingPrice, Currency,
                                                                      Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                      false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                      Width, Length, Height, Weight, Desi,
                                                                      FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                      true, Model, Amount, AmountOnRoad);
                                        }
                                        //Logger.Write("Product Updated : ProductId => " + productId.ToString(), "Trace");
                                    }

                                    #endregion

                                    //ana ürünmü yoksa alt ürünmü belirleyelim
                                    int ustUrunId = dbProduct.GetVariantId(productId);


                                    if (NewProduct || xml.ReInstallProductImg)
                                    {
                                        #region New Product to Update Image

                                        if (productId > 0 && ustUrunId == 0)
                                        {
                                            short resimNo = 1;
                                            if (!string.IsNullOrEmpty(UrunResim))
                                            {
                                                try
                                                {
                                                    DownloadImage(productId, UrunResim, resimNo);
                                                    resimNo++;
                                                }
                                                catch
                                                {
                                                    Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim, "Exception");
                                                    sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + UrunResim);
                                                }
                                            }
                                        }

                                        #endregion
                                    }


                                    if (productId > 0)
                                    {
                                        #region Stok Kart Ekstra Alanlar

                                        foreach (var productinfo in product.Descendants("ps").Descendants("s"))
                                        {
                                            string type = HttpUtility.HtmlDecode(XEResultString(productinfo, "quest"));
                                            string Information = HttpUtility.HtmlDecode(XEResultString(productinfo, "val"));

                                            dbProductInfo.Insert(productId, type, Information);
                                        }

                                        #endregion

                                        #region Stok Kart Ekstra Gruplar

                                        foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                        {
                                            dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                        }

                                        #endregion
                                    }
                                }

                                dbProduct.SetInactive(xml.XmlIdForProductId);
                                Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                                #endregion

                                #endregion
                            }
                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("OPERA") && xml.Description.ToUpperInvariant().Contains("STANBUL"))
                        {
                            #region OPERA İSTANBUL

                            List<XElement> productList = xDoc.Descendants("root").Descendants("item").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {
                                #region Sample XML
                                /*
                                 <root>
                                     <item>
                                      <id>23</id>
                                      <stockCode><![CDATA[CYBX.513117008]]></stockCode>
                                      <label><![CDATA[SOLUTION X2 FIX 15-36 OTO KOLTUGU (POPPY RED)]]></label>
                                      <status>1</status>
                                      <brand><![CDATA[CYBEX]]></brand>
                                      <brandId>118</brandId>
                                      <brandDistCode><![CDATA[0118BESd]]></brandDistCode>
                                      <mainCategory><![CDATA[Cybex]]></mainCategory>
                                      <mainCategoryId>164</mainCategoryId>
                                      <mainCategoryDistCode><![CDATA[0164Lkuv]]></mainCategoryDistCode>
                                      <category><![CDATA[]]></category>
                                      <categoryId/>
                                      <categoryDistCode><![CDATA[]]></categoryDistCode>
                                      <subCategory><![CDATA[]]></subCategory>
                                      <subCategoryId/>
                                      <subCategoryDistCode><![CDATA[]]></subCategoryDistCode>
                                      <isOptionedProduct>0</isOptionedProduct>
                                      <isOptionOfAProduct>0</isOptionOfAProduct>
                                      <rootProductId>0</rootProductId>
                                      <rootProductStockCode><![CDATA[0]]></rootProductStockCode>
                                      <marketPrice><![CDATA[]]></marketPrice>
                                      <price1>422.881</price1>
                                      <tax>18</tax>
                                      <currencyAbbr>TL</currencyAbbr>
                                      <rebatePercent>0.00000</rebatePercent>
                                      <moneyOrder>0</moneyOrder>
                                      <stockAmount>10</stockAmount>
                                      <stock><![CDATA[ var ]]></stock>
                                      <stockType><![CDATA[Adet]]></stockType>
                                      <stockTypeId><![CDATA[1]]></stockTypeId>
                                      <warranty>0</warranty>
                                      <picture1Path><![CDATA[http://www.operaistanbul.com/modules/catalog/products/pr_01_23_max.jpg?rev=1390382493]]></picture1Path>
                                      <picture2Path><![CDATA[http://www.operaistanbul.com/modules/catalog/products/pr_02_23_max.jpg?rev=1387381315]]></picture2Path>
                                      <picture3Path><![CDATA[http://www.operaistanbul.com/modules/catalog/products/pr_03_23_max.jpg?rev=1387381316]]></picture3Path>
                                      <picture4Path><![CDATA[http://www.operaistanbul.com/modules/catalog/products/pr_04_23_max.jpg?rev=1387381319]]></picture4Path>
                                      <dm3>0.00</dm3>
                                      <details><![CDATA[ LOREM İPSUM VE HTML İÇERİĞİ ]]></details>
                                      <productLink><![CDATA[http://www.operaistanbul.com/SOLUTION-X2-FIX-15-36-OTO-KOLTUGU-POPPY-RED,PR-23.html]]></productLink>
                                      <categoryTree><![CDATA[Cybex]]></categoryTree>
                                      <productCategoryId>164</productCategoryId>
                                      <productCategoryLabel><![CDATA[Cybex]]></productCategoryLabel>
                                      <priceWithTax>499.00</priceWithTax>
                                      <priceTaxWithCur>499.00</priceTaxWithCur>
                                      <priceEft>499.00</priceEft>
                                      <priceRebateWithTax>499.00</priceRebateWithTax>
                                      <priceRebateWithMoneyOrderWithTax>499.00</priceRebateWithMoneyOrderWithTax>
                                      <rebatedPriceWithoutTax>422.88</rebatedPriceWithoutTax>
                                      <rebatedPriceWithMoneyOrderWithoutTax>422.88</rebatedPriceWithMoneyOrderWithoutTax>
                                      <rebate>0.00000</rebate>
                                      <rebateType>1</rebateType>
                                      <multipleOptions><![CDATA[]]></multipleOptions>
                                      <shortdetails><![CDATA[]]></shortdetails>
                                      <title><![CDATA[]]></title>
                                      <keywords><![CDATA[]]></keywords>
                                      <description><![CDATA[]]></description>
                                     </item>
                                  <root>
                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                int categoryID = XEResultInt(product, "mainCategoryId");
                                string groupname = XEResultString(product, "mainCategory");
                                string groupname2 = categoryID.ToString() + '-' + groupname;
                                string categoryName = XEResultString(product, "category");
                                if (!string.IsNullOrEmpty(categoryName))
                                {
                                    groupname2 += " - " + categoryName;
                                }
                                string brand = XEResultString(product, "brand");

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                ProcessedProductCode = XEResultString(product, "stockCode");
                                string DealerProductId = ProcessedProductCode;
                                string ProductId = XEResultString(product, "id");
                                string ImageUrl1 = XEResultString(product, "picture1Path");
                                string ImageUrl2 = XEResultString(product, "picture2Path");
                                string ImageUrl3 = XEResultString(product, "picture3Path");
                                string ImageUrl4 = XEResultString(product, "picture4Path");

                                string Description = HttpUtility.HtmlDecode(XEResultString(product, "details"));
                                string Tax = XEResultString(product, "tax");
                                string ProductName = XEResultString(product, "label");
                                decimal Price = XEResultDecimal(product, "price1", xml.DecimalPoint);
                                decimal Amount = XEResultDecimal(product, "stockAmount", xml.DecimalPoint);
                                decimal AmountOnRoad = 0; //XEResultDecimal(product, "AmountOnRoad", xml.DecimalPoint);
                                decimal BuyingPrice = Convert.ToDecimal(Convert.ToDouble(Price) * 0.8);
                                string Barcode = XEResultString(product, "stockCode");
                                string Currency = ChangeExchangeCode(XEResultString(product, "currencyAbbr"));
                                //int xmlBrandId = xmlBrand.Id;
                                //int xmlGroupId = xmlImportGroup2.Id;


                                //if (BuyingPrice > 0)
                                //{
                                //    Price = Math.Round(BuyingPrice * xmlBrand.ProfitRate, 2);
                                //}
                                //else
                                //{
                                //    Price = Math.Round(Price * xml.ProfitRate, 2);
                                //}

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                short DeliveryTime = xml.DeliveryTime;
                                decimal Desi = 0;
                                if (xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }

                                decimal CargoPrice = xml.CargoPrice == 0 ? 0 : xml.CargoPrice;
                                bool FreeCargo = (xml.LimitForFreeCargo > 0 && Price >= xml.LimitForFreeCargo);
                                bool FastCargo = true;
                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }

                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }
                                bool NewProduct = false;
                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    //Logger.Write("XML Import Product Insert : " + ProductId + " - " + ProductName, "Trace");

                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                                                                  Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                              Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, DealerProductId, Barcode, ProductName, category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency,
                              Description, xml.ReloadDescription, false, 0, "", "Gün", DeliveryTime, 0, 0, 0, 0, Desi, FastCargo, FreeCargo, false, CargoPrice, 0, (Amount + AmountOnRoad) > 0, "", Amount, AmountOnRoad);
                                    }
                                }
                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0 && !string.IsNullOrEmpty(ImageUrl1))
                                    {
                                        Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                        try
                                        {
                                            DownloadImage(productId, ImageUrl1, 1);
                                        }
                                        catch
                                        {
                                            Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl1, "Exception");
                                            sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl1);
                                        }
                                    }
                                    if (productId > 0 && !string.IsNullOrEmpty(ImageUrl2))
                                    {
                                        Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                        try
                                        {
                                            DownloadImage(productId, ImageUrl2, 2);
                                        }
                                        catch
                                        {
                                            Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2, "Exception");
                                            sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl2);
                                        }
                                    }
                                    if (productId > 0 && !string.IsNullOrEmpty(ImageUrl3))
                                    {
                                        Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                        try
                                        {
                                            DownloadImage(productId, ImageUrl3, 3);
                                        }
                                        catch
                                        {
                                            Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3, "Exception");
                                            sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl3);
                                        }
                                    }
                                    if (productId > 0 && !string.IsNullOrEmpty(ImageUrl4))
                                    {
                                        Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                        try
                                        {
                                            DownloadImage(productId, ImageUrl4, 4);
                                        }
                                        catch
                                        {
                                            Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl4, "Exception");
                                            sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl4);
                                        }
                                    }

                                    #endregion
                                }
                                if (productId > 0)
                                {
                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("BUTİGİM XML") || xml.Description.ToUpperInvariant().Contains("BUTIGIM XML"))
                        {
                            #region Butigim

                            List<XElement> productList = xDoc.Descendants("urunler").Descendants("urun").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {
                                #region Sample XML
                                /*
                                  <urunler>
                                      <urun>
                                        <urunKodu>SA-E-13-00219</urunKodu>
                                        <urunAdi>SA-E-13-00219 Yeşil-Haki Erkek Kol Saati</urunAdi>
                                        <markaId>1002</markaId>
                                        <kategoriId>102</kategoriId>
                                        <ekstraAlanlar>
                                          <alan>
                                            <isim>Cinsiyet</isim>
                                            <deger>Erkek</deger>
                                          </alan>
                                          <alan>
                                            <isim>Kasa Şekli</isim>
                                            <deger>Yuvarlak</deger>
                                          </alan>
                                          <alan>
                                            <isim>Kordon Tipi</isim>
                                            <deger>Silikon-Plastik</deger>
                                          </alan>
                                          <alan>
                                            <isim>Kordon Rengi</isim>
                                            <deger>Yeşil-Haki</deger>
                                          </alan>
                                          <alan>
                                            <isim>Kasa Rengi</isim>
                                            <deger>Altın</deger>
                                          </alan>
                                          <alan>
                                            <isim>Kadran İç Rengi</isim>
                                            <deger>Koyu</deger>
                                          </alan>
                                          <alan>
                                            <isim>Gösterge</isim>
                                            <deger>Analog</deger>
                                          </alan>
                                          <alan>
                                            <isim>Kronometre</isim>
                                            <deger>Yok</deger>
                                          </alan>
                                          <alan>
                                            <isim>Alarm</isim>
                                            <deger>Yok</deger>
                                          </alan>
                                          <alan>
                                            <isim>Takvim</isim>
                                            <deger>Yok</deger>
                                          </alan>
                                        </ekstraAlanlar>
                                        <stok>0</stok>
                                        <stokYolda>10</stokYolda>
                                        <resim>http://butigim.com/admin/uplfiles/B_6200807-01072014162749.jpg</resim>
                                        <fiyat>19,9</fiyat>
                                      </urun>
                                    </urunler>

                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                ProcessedProductCode = XEResultString(product, "urunKodu");
                                Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                CategoryMeta ktMeta = dbCategory.GetMeta(XEResultInt(product, "kategoriId"));
                                string groupname = ktMeta.CategoryName;
                                string groupname2 = xml.XmlIdForProductId.ToString() + '-' + groupname;
                                CategoryMeta brMeta = dbCategory.GetMeta(XEResultInt(product, "markaId"));
                                string brand = brMeta.CategoryName;

                                #region Category Group Control

                                XmlImportGroup xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlIdForProductId, groupname2);
                                if (xmlImportGroup2 == null)
                                {
                                    int altGrupId = dbCategory.GetByName(groupname);

                                    Logger.Write("XML Import Group Insert : " + groupname2 + " => " + altGrupId.ToString(), "Trace");

                                    if (altGrupId > 0)
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, altGrupId, false);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertGroup(xml.XmlId, groupname2, 0, false);
                                    }
                                    xmlImportGroup2 = dbXmlImport.GetGroup(xml.XmlId, groupname2);
                                    sbReport.Append("Grup Oluşturuldu : " + groupname2);
                                }
                                Category category2 = dbCategory.Get(xmlImportGroup2.GroupId);
                                if (!xmlImportGroup2.IsActive || category2 == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Brand Control

                                XmlImportBrand xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                if (xmlBrand == null)
                                {
                                    int brandId = dbCategory.GetByName(brand);

                                    Logger.Write("XML Import Brand Insert : (" + groupname2 + ") " + brand + " => " + brandId.ToString(), "Trace");

                                    if (brandId > 0)
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, brandId, false, xml.ProfitRate);
                                        xmlBrand = dbXmlImport.GetBrand(xmlImportGroup2.Id, brand);
                                    }
                                    else
                                    {
                                        dbXmlImport.InsertBrand(xmlImportGroup2.Id, brand, 0, false, xml.ProfitRate);
                                        continue;
                                    }
                                    sbReport.Append("Marka Oluşturuldu : " + brand + " (" + groupname2 + ")");
                                }
                                Category brandGroup = dbCategory.Get(xmlBrand.BrandId);
                                if (!xmlBrand.IsActive || brandGroup == null)
                                {
                                    continue;
                                }

                                #endregion

                                #region Vars

                                string ProductCode = ProcessedProductCode;
                                string ProductId = ProductCode;
                                string ProductName = XEResultString(product, "urunAdi");
                                string Tax = "18";
                                string Currency = "TL";
                                decimal Price = XEResultDecimal(product, "fiyat", xml.DecimalPoint);
                                decimal BuyingPrice = 0;
                                string Model = "";
                                string Description = "";
                                string WarantyPeriod = "Yıl";
                                int WarantyTime = 0;
                                string DeliveryPeriod = "Gün";
                                int DeliveryTime = 0;
                                decimal CargoPriceField = 0;
                                decimal CargoPriceAdditionField = 0;
                                bool FreeCargo = false;
                                bool FastCargo = false;
                                bool NewProduct = false;
                                decimal Desi = 0;
                                if (string.IsNullOrEmpty(Convert.ToString(xmlImportGroup2.Desi)) || xmlImportGroup2.Desi == 0)
                                {
                                    Desi = xml.Desi == 0 ? 0 : xml.Desi;
                                }
                                else
                                {
                                    Desi = xmlImportGroup2.Desi;
                                }
                                decimal Weight = 0;
                                decimal Width = 0;
                                decimal Length = 0;
                                decimal Height = 0;

                                decimal Amount = XEResultInt(product, "stok");
                                decimal AmountOnRoad = XEResultInt(product, "stokYolda");

                                if (Amount == 0)
                                {
                                    Amount = xml.Amount;
                                    if (Amount == 0)
                                    {
                                        FastCargo = false;
                                    }
                                }
                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }

                                Price = (Price / 118) * 100;
                                Price = Math.Round(Price * xmlBrand.ProfitRate, 4);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                #endregion

                                int productId = dbProduct.GetByXMLProductId(xml.XmlIdForProductId, ProductId);

                                if (productId == -2)
                                {
                                    productId = dbProduct.GetByXMLProductId_2(xml.XmlIdForProductId, ProductId);
                                    if (productId > 0)
                                    {
                                        dbProduct.UpdateAmount(productId, xml.XmlIdForProductId, FastCargo, Amount, AmountOnRoad);
                                    }
                                    continue;
                                }

                                if (productId == -1 && xml.InsertNewProduct)
                                {
                                    //Logger.Write("Product Insert : " + ProductId + " - " + ProductName, "Trace");
                                    productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                  category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, BuyingPrice, Currency, "", xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);

                                    //Logger.Write("Product Inserted : ProductId => " + productId.ToString(), "Trace");
                                    NewProduct = true;
                                    newProductCounter++;
                                }
                                else
                                {
                                    //Logger.Write("Product Update : " + productId.ToString() + " " + ProductId + " - " + ProductName, "Trace");
                                    if (xml.StkNameNotUpdate)
                                    {
                                        productId = dbProduct.InsertWithoutProductName(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode,
                                                                  category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, 0, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    else
                                    {
                                        productId = dbProduct.Insert2(xml.XmlIdForProductId, ProductId, ProductCode, ProductCode, ProductName,
                                                                  category2.CategoryId, brandGroup.CategoryId, decimal.Parse(Tax), "AD", Price, 0, Currency,
                                                                  Description.Replace("<br />", "\r\n"), xml.ReloadDescription,
                                                                  false, (short)WarantyTime, WarantyPeriod, DeliveryPeriod, (short)DeliveryTime,
                                                                  Width, Length, Height, Weight, Desi,
                                                                  FastCargo, FreeCargo, NewProduct, CargoPriceField, CargoPriceAdditionField,
                                                                  true, Model, Amount, AmountOnRoad);
                                    }
                                    //Logger.Write("Product Updated : ProductId => " + productId.ToString(), "Trace");
                                }
                                if (NewProduct || xml.ReInstallProductImg)
                                {
                                    #region New Product to Update Image

                                    if (productId > 0)
                                    {
                                        string ImageUrl = XEResultString(product, "resim");
                                        if (!string.IsNullOrEmpty(ImageUrl))
                                        {
                                            Logger.Write("XML Import Product Image Downloading : ProductId => " + productId.ToString(), "Trace");
                                            try
                                            {
                                                DownloadImage(productId, ImageUrl, 1, 0, false, true);
                                            }
                                            catch
                                            {
                                                Logger.Write("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl, "Exception");
                                                sb.Append("XML Import Product Image Downloading Error: ProductId => " + productId.ToString() + " " + ImageUrl);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Write("XML Import Product Image Info Not Found: ProductId => " + productId.ToString(), "Exception");
                                            sb.Append("XML Import Product Image Info Not Found: ProductId => " + productId.ToString());
                                        }
                                    }

                                    #endregion
                                }


                                if (productId > 0)
                                {
                                    #region Stok Kart Ekstra Alanlar

                                    foreach (var productinfo in product.Descendants("ekstraAlanlar").Descendants("alan"))
                                    {
                                        string type = HttpUtility.HtmlDecode(XEResultString(productinfo, "isim"));
                                        string Information = HttpUtility.HtmlDecode(XEResultString(productinfo, "deger"));

                                        if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(Information))
                                        {
                                            dbProductInfo.Insert(productId, type, Information);
                                        }
                                    }

                                    #endregion

                                    #region Stok Kart Ekstra Gruplar

                                    foreach (XmlImportGroupAdd groupAdd in xmlImportGroup2.XmlImportGroupAdds)
                                    {
                                        dbProduct.InsertGroup(productId, groupAdd.CategoryId, "D");
                                    }

                                    #endregion
                                }
                            }

                            dbProduct.SetInactive(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stok Bulunmayan Kayıtlar Pasif Yapıldı!", "Trace");

                            #endregion
                        }
                        else if (xml.Description.ToUpperInvariant().Contains("NEBIM") || !xml.Description.ToUpperInvariant().Contains("NEBİM"))
                        {
                            #region Nebim

                            List<XElement> productList = xDoc.Descendants("MerchantItems").Descendants("MerchantItem").ToList();

                            Logger.Write("XML Import Kayıt Sayısı : " + productList.Count.ToString(), "Trace");

                            dbProduct.ResetAmount(xml.XmlIdForProductId);
                            Logger.Write("XML Import Stoklar Resetlendi !", "Trace");

                            foreach (var product in productList)
                            {
                                #region Sample XML
                                /*
                                    <MerchantItem>
                                 *      <merchantItemId>{MerchantItemId}</merchantItemId>
                                 *      <merchantItemCode>{MerchantItemCode}</merchantItemCode> -> eşleştir
                                 *      <merchantItemCategoryName>{MerchantItemCategoryName}</merchantItemCategoryName>
                                 *      <brand>{Brand}</brand>
                                 *      <itemTitle>{ItemTitle}</itemTitle>
                                 *      <pricePlusTax>{PricePlusT,ax}</pricePlusTax> 
                                 *      <price>{Pri,ce}</price> -> fiyatı al
                                 *      <tax>{Ta,x}</tax> -> kdv al sıfır değilse güncelle
                                 *      <currency>{Currency}</currency> -> kur al
                                 *      <amount>{Amount}</amount> -> adet al (yolda)
                                 *  </MerchantItem>
                                 */

                                #endregion

                                #region Processed Product Count Log

                                ProductCount++;
                                if (ProductCount % 100 == 0)
                                {
                                    Logger.Write(ProductCount.ToString() + " Adet Ürün İşlem Gördü", "Trace");
                                }

                                #endregion

                                ProcessedProductCode = XEResultString(product, "merchantItemCode");
                                Logger.Write("Product Process Started Dealer ProductCode: " + ProcessedProductCode, "Trace");

                                string groupname = XEResultString(product, "merchantItemCategoryName");
                                string groupname2 = groupname;
                                string brand = XEResultString(product, "brand");

                                #region Vars

                                string ProductCode = ProcessedProductCode;
                                string ProductName = XEResultString(product, "itemTitle");
                                string ProductId = XEResultString(product, "merchantItemId").Replace("-", "");
                                decimal Tax = XEResultDecimal(product, "tax", xml.DecimalPoint);
                                decimal Price = XEResultDecimal(product, "price", xml.DecimalPoint);
                                string Currency = ChangeExchangeCode(XEResultString(product, "currency"));
                                decimal AmountOnRoad = XEResultDecimal(product, "amount", xml.DecimalPoint);

                                Price = Math.Round(Price * xml.ProfitRate, 2);

                                if (xml.PriceLimit > 0 && xml.PriceLimit >= Price)
                                {
                                    Price += xml.PriceToAdd;
                                }
                                if (xml.PriceToAddAll > 0)
                                {
                                    Price += xml.PriceToAddAll;
                                }

                                if (AmountOnRoad == 0)
                                {
                                    AmountOnRoad = xml.AmountOnRoad;
                                }

                                #endregion


                                if (!string.IsNullOrEmpty(ProductCode) && Price > 0)
                                {
                                    dbProduct.UpdateNebimXmlProducts(ProductCode, xml.XmlId, Tax, Price, AmountOnRoad);
                                }
                            }
                            #endregion
                        }
                        Logger.Write("XML Import " + xml.Description + " Tamamlandı", "Trace");
                    }
                    else
                    {
                        Logger.Write("XML Import Dosyası Alınamadı, Tekrar Deneyiniz !", "Trace");
                        sb.Append("XML Import Dosyası Alınamadı, Tekrar Deneyiniz !");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write("ProcessedProductCode : " + ProcessedProductCode + " -> " + ex.Message, "Exception");
                sb.Append("ProcessedProductCode : " + ProcessedProductCode + " -> " + ex.Message);
                sb.Append("XML Import son alınan hatadan sonra durduruldu!");
            }

            #region Report Mail

            string mailbody;
            string subject;
            if (sb.Length > 0)
            {
                subject = xml.Description + " : XML Import Islemi Aşağıdaki Hatalarla Tamamlandi";
                mailbody = "XML Import Islemi Aşağıdaki Hatalarla Tamamlandi" + Environment.NewLine + sb.ToString();
            }
            else
            {
                subject = xml.Description + " : XML Import Islemi Başarıyla Tamamlandi";
                mailbody = "XML Import Islemi Başarıyla Tamamlandi.";
            }
            if (sbReport.Length > 0)
            {
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Oluşturulan Grup ve Markaların Listesi :" + Environment.NewLine + sbReport.ToString();
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Eklenen Yeni Ürün Sayısı : " + newProductCounter.ToString();
            }
            //string fiyatSifir = "";
            //string kategoriSifir = "";
            //string markaSifir = "";
            //string ekstraSifir = "";
            //string ekstraDetaySifir = "";
            if (string.IsNullOrEmpty(fiyatSifir))
            {
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Fiyat bilgisi bulunmayan ürünlerin kodları : " + fiyatSifir;
            }
            if (string.IsNullOrEmpty(kategoriSifir))
            {
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Kategori bilgisi bulunmayan ürünlerin kodları : " + kategoriSifir;
            }
            if (string.IsNullOrEmpty(markaSifir))
            {
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Marka bilgisi bulunmayan ürünlerin kodları : " + markaSifir;
            }
            if (string.IsNullOrEmpty(ekstraSifir))
            {
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Ekstra bilgisi bulunmayan ürünlerin kodları : " + ekstraSifir;
            }
            if (string.IsNullOrEmpty(ekstraDetaySifir))
            {
                mailbody = mailbody + Environment.NewLine + Environment.NewLine + "Ekstra detay bilgisi bulunmayan ürünlerin kodları : " + ekstraDetaySifir;
            }
            if (!string.IsNullOrEmpty(Parameters.XmlImportMessagesToAddress))
            {
                try
                {
                    Utils.SendMail(Parameters.XmlImportMessagesToAddress, "", "", subject, mailbody, false);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex, "Exception");
                }
            }

            #endregion
        }

        #endregion

        #region XEResults

        private static string XEResultString(XElement xe, string Attribute)
        {
            try
            {
                return xe.Descendants(Attribute).FirstOrDefault().Value ?? "";
            }
            catch
            {
                return "";
            }
        }

        private static string XEAttributeResultString(XElement xe, string Attribute)
        {
            try
            {
                return xe.Attributes(Attribute).FirstOrDefault().Value ?? "";
            }
            catch
            {
                return "";
            }
        }

        private static string XEResultStringWin1254(XElement xe, string Attribute)
        {
            try
            {
                Encoding iso = Encoding.GetEncoding("ISO-8859-1");
                Encoding defaultE = Encoding.Default;
                string msg = defaultE.GetString(iso.GetBytes(xe.Descendants(Attribute).FirstOrDefault().Value ?? ""));

                return msg;
            }
            catch
            {
                return "";
            }
        }

        private static int XEResultInt(XElement xe, string Attribute)
        {
            try
            {
                return Convert.ToInt32(xe.Descendants(Attribute).FirstOrDefault().Value ?? "0");
            }
            catch
            {
                return 0;
            }
        }

        private static decimal XEResultDecimal(XElement xe, string Attribute, string DecimalPoint)
        {
            try
            {
                if (DecimalPoint == ".")
                    return Convert.ToDecimal(xe.Descendants(Attribute).FirstOrDefault().Value ?? "0", new CultureInfo("en-US"));
                else if (DecimalPoint == "")
                    return Convert.ToDecimal(xe.Descendants(Attribute).FirstOrDefault().Value ?? "0") / 100;
                else
                    return Convert.ToDecimal(xe.Descendants(Attribute).FirstOrDefault().Value.Replace(DecimalPoint, "."), new CultureInfo("en-US"));
            }
            catch
            {
                return 0;
            }
        }

        private static decimal XEAttributeResultDecimal(XElement xe, string Attribute, string DecimalPoint)
        {
            try
            {
                if (DecimalPoint == ".")
                    return Convert.ToDecimal(xe.Attributes(Attribute).FirstOrDefault().Value ?? "0", new CultureInfo("en-US"));
                else if (DecimalPoint == "")
                    return Convert.ToDecimal(xe.Attributes(Attribute).FirstOrDefault().Value ?? "0") / 100;
                else
                    return Convert.ToDecimal(xe.Attributes(Attribute).FirstOrDefault().Value.Replace(DecimalPoint, "."), new CultureInfo("en-US"));
            }
            catch
            {
                return 0;
            }
        }

        private static bool XEResultBool(XElement xe, string Attribute)
        {
            try
            {
                if (xe.Descendants(Attribute).FirstOrDefault().Value != null &&
                   (xe.Descendants(Attribute).FirstOrDefault().Value.ToLowerInvariant() == "true" || xe.Descendants(Attribute).FirstOrDefault().Value == "1")
                   )
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region ConnectRestEC

        private static string ConnectRestEC(Uri addr, out bool Success)
        {
            string result = string.Empty;
            Success = false;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(addr);
                request.KeepAlive = false;
                request.Timeout = 120000; //2 min
                request.Method = "GET";
                request.ContentLength = 0;
                using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
                {
                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader reader;
                        if (addr.Host.Contains("gama") || addr.Host.Contains("toptanciniz"))
                        {
                            reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-9"));
                        }
                        else
                        {
                            reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
                        }
                        result = reader.ReadToEnd();
                        Success = true;
                    }

                }
                return result;
            }
            catch (Exception ex)
            {
                Logger.Write(ex, "Exception");
                return result = "Time Out Exception";
            }
        }

        #endregion

        #endregion

        #region RefreshParameters

        [HttpPost]
        public ActionResult RefreshParameters(string Password)
        {
            if (!string.IsNullOrEmpty(Password))
            {
                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    dbRefs.RefreshSiteParameters();
                    return Content("OK");
                }
                else
                {
                    return Content("Parametreleri Kontrol Ediniz.");
                }
            }
            else
            {
                return Content("Parametreleri Kontrol Ediniz.");
            }
        }

        #endregion

        #region TCMBDovizKurAl

        private static IList<ExchangeRate> TCMBDovizKurAl()
        {
            IList<ExchangeRate> exchangeRates = new List<ExchangeRate>();

            XDocument TCMB = XDocument.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
            try
            {
                if (TCMB != null)
                {
                    var Kur = (from p in TCMB.Element("Tarih_Date").Elements("Currency")
                               select new
                               {
                                   tarih = (string)TCMB.Element("Tarih_Date").Attribute("Tarih"),
                                   kod = (string)p.Attribute("Kod"),
                                   isim = (string)p.Element("Isim"),
                                   alis = (string)p.Element("ForexBuying"),
                                   satis = (string)p.Element("ForexSelling"),
                                   efektifalis = (string)p.Element("BanknoteBuying"),
                                   efektifsatis = (string)p.Element("BanknoteSelling")
                               });

                    if (Kur.AsEnumerable().Count() > 0)
                    {
                        foreach (var item in Kur)
                        {
                            exchangeRates.Add(new ExchangeRate { ExchangeId = item.kod, ExchangeName = item.isim, Rate = Decimal.Parse(string.IsNullOrEmpty(item.satis) ? "0" : item.satis, new CultureInfo("en-US")) });
                            //dbExchangeRate.Insert(item.kod, Parameters.DefaultExchangeType, DateTime.Today, Decimal.Parse(item.satis), "Import");
                            //HttpContext.Current.Response.Write(item.tarih + " / " + item.kod + " / " + item.isim + " / " + item.alis + " / " + item.satis + " / " + item.efektifalis + " / " + item.efektifsatis + "<br />");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write(ex, "Exception");
            }
            return exchangeRates;
        }

        #endregion

        #region GetRate

        private decimal GetRate(IList<ExchangeRate> ExchangeRates, IList<ExchangeRate> TCMBExchangeRates, string ExchangeId)
        {
            decimal rate = 0;
            ExchangeRate eRate = ExchangeRates.Where(r => r.ExchangeId == ExchangeId).FirstOrDefault();

            if (eRate != null && eRate.Rate > 0)
            {
                rate = eRate.Rate;
            }
            else
            {
                if (TCMBExchangeRates == null || TCMBExchangeRates.Count == 0)
                {
                    foreach (ExchangeRate exc in TCMBDovizKurAl())
                    {
                        TCMBExchangeRates.Add(exc);
                    }
                }
                ExchangeRate tcmbRate = TCMBExchangeRates.Where(r => r.ExchangeId == ExchangeId).FirstOrDefault();
                if (tcmbRate != null && tcmbRate.Rate > 0)
                {
                    rate = tcmbRate.Rate;
                    dbExchangeRate.Insert(tcmbRate.ExchangeId, tcmbRate.ExchangeName, Parameters.DefaultExchangeType, DateTime.Today, rate, "Import");
                    ExchangeRates.Add(new ExchangeRate { ExchangeId = ExchangeId, ExchangeType = Parameters.DefaultExchangeType, ExchangeName = tcmbRate.ExchangeName, Rate = rate, ExchangeDate = DateTime.Today });
                }
            }
            return rate;
        }

        #endregion

        #region DownloadImage

        private void DownloadImage(int productId, string imageUrl, short imageNo, int rotateImage = 0, bool onlyRotateWides = true, bool cropImage = false)
        {
            var request = WebRequest.Create(imageUrl);
            Image img;
            using (var response = request.GetResponse())
            using (var stream = response.GetResponseStream())
            {
                img = Bitmap.FromStream(stream);
            }

            string ImageSaveMessage = SaveImage(img, productId, "Product", imageNo, "", rotateImage, onlyRotateWides, true);

            if (ImageSaveMessage == "Resim Kaydedildi.")
            {
                dbProduct.InsertImage(productId, imageNo);
            }
        }

        #endregion

        #region DownloadFormImage

        private void DownloadFormImage(int productId, Image img, short imageNo, int rotateImage = 0, bool onlyRotateWides = true, bool cropImage = false)
        {
            string ImageSaveMessage = SaveImage(img, productId, "Product", imageNo, "", rotateImage, onlyRotateWides, true);

            if (ImageSaveMessage == "Resim Kaydedildi.")
            {
                dbProduct.InsertImage(productId, imageNo);
            }
        }

        #endregion

        #region ChangeExchangeCode

        public string ChangeExchangeCode(string ExchangeCode)
        {
            if (ExchangeCode == null) ExchangeCode = "";
            return ExchangeCode.ToUpperInvariant().Replace("TRL", "TL").Replace("YTL", "TL").Replace("EURO", "EUR");
        }

        #endregion

        #region Group Codes

        public ActionResult NewGroupCode(int pwd, int start, string gruptip = "")
        {
            if (pwd == 1105613031)
            {
                IList<Category> categories = dbCategory.GetByType(gruptip);
                ViewBag.Start = start.ToString();
                ViewBag.Process = "<table><tr><td>ID</td><td>NAME</td><td><b>CODE</b></td></tr>";
                foreach (var cat in categories)
                {
                    dbCategory.UpdateGroupCode(cat.CategoryId, start.ToString());
                    ViewBag.Process += "<tr><td>" + cat.CategoryId.ToString() + "</td><td>" + cat.CategoryName + "</td><td><b>Atanan Grup Kodu: " + start.ToString() + "</b></td></tr>";
                    start++;
                }
                ViewBag.Process += "</table>";
                ViewBag.End = (start - 1).ToString();
                ViewBag.Count = categories.Count().ToString();
                ViewBag.Gruptip = gruptip;
            }
            return View();
        }

        public ActionResult UpdateProductCode(int pwd, int type, int categoryId)
        {
            if (pwd == 1105613031)
            {
                IList<Product> products = dbProduct.GetListFull(categoryId, 1, 0, -1, "");
                var basarili = 0;
                var basarisiz = 0;
                var basarisizlar = "";
                var sifirlamaBasla = 100000;
                var sayyac = 1;

                foreach (var pro in products)
                {
                    //Atlama yapcaksak id yazarız
                    //if (pro.ProductId < 3976)
                    //{
                    //    continue;
                    //}
                    if (type == 1)
                    {
                        //sıfırlama
                        int res = dbProduct.ResetProductCode(pro.ProductId, sifirlamaBasla.ToString());
                        sifirlamaBasla++;
                        if (sifirlamaBasla % 1000 == 0)
                        {
                            ///asdasdasd
                        }
                    }
                    else if (type == 2)
                    {
                        //atama
                        int res = dbProduct.UpdateProductCode(pro.ProductId);
                        if (res == 1)
                        {
                            basarili++;
                        }
                        else
                        {
                            basarisiz++;
                            basarisizlar += pro.ProductId.ToString() + ", ";
                        }
                        if (sayyac % 1000 == 0)
                        {
                            ///asdasdasd
                        }
                        sayyac++;
                    }
                }
                ViewBag.Count = products.Count().ToString();
                ViewBag.Basarili = basarili.ToString();
                ViewBag.Basarisiz = basarisiz.ToString();
                ViewBag.Basarisizlar = basarisizlar;
            }
            return View();
        }

        #endregion

        #region CompleteExtraFields

        public ActionResult CompleteExtraFields(string pwd, int groupId, int altDahil)
        {
            pwd = pwd.Replace("\r\n", "");
            if (pwd == dbRefs.GetRef1Old(1911))
            {

                try
                {
                    Category ct = dbCategory.Get(groupId);
                    IList<Product> Products = dbProduct.GetListFullOnlyMain(groupId, altDahil, 0, -1, "");
                    foreach (Product pr in Products)
                    {
                        //stok grup ekstra getir o kategori için
                        IList<Property> Properties = dbProduct.GetPropertiesList(pr.CategoryId).ToList<Property>();

                        //stok grup ekstrada kayıt varsa
                        if (Properties.Count() > 0)
                        {
                            //stok kart ekstra getir
                            IList<ProductInfo> Infos = dbProductInfo.GetList(pr.ProductId);

                            //stok kartta hiç ekstra alan yoksa
                            if (Infos.Count() < 1)
                            {
                                //grup ekstra alanlarında dön
                                foreach (Property pt in Properties)
                                {
                                    //insert
                                    if ((Infos.Where(o => o.Type == pt.Aciklama).Count()) <= 0)
                                    {
                                        dbProductInfo.InsertDirect(pr.ProductId, pt.Aciklama, "");
                                    }
                                }
                            }
                        }

                    }
                }
                catch
                {

                }
            }
            return Content("Islem tamamlandi.");
        }

        #endregion

        #region MailSender
        [HttpPost]
        public ActionResult MailSender(string Password, string ReturnMessage, string ErrorReturnMessage, string to, string cc, string bcc, string subject, string body, short UseHtml, HttpPostedFileBase file = null)
        {
            try
            {
                bool IsHtml = UseHtml == 1 ? true : false;
                Logger.Write("Send Mail -> Pass:" + Password + "");
                Password = Password.Replace("\r\n", "");
                if (Password == dbRefs.GetRef1Old(1911))
                {
                    //Encoding iso = Encoding.GetEncoding("ISO-8859-1");
                    //Encoding utf8 = Encoding.UTF8;
                    //byte[] isoBytes = iso.GetBytes(body);
                    //byte[] utfBytes = Encoding.Convert(iso, utf8, isoBytes);
                    //byte[] utfBytes = utf8.GetBytes(body);
                    //byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);

                    //string msgbody = iso.GetString(isoBytes);


                    Logger.Write("Send Mail -> Password Match", "Trace");
                    if (file != null)
                    {
                        Utils.SendMail(to, cc, bcc, Utils.HtmlTurkishChars(Utils.HtmlTurkishChars(subject)), Utils.HtmlTurkishChars(body), IsHtml, file);
                    }
                    else
                    {
                        Utils.SendMail(to, cc, bcc, Utils.HtmlTurkishChars(Utils.HtmlTurkishChars(subject)), Utils.HtmlTurkishChars(body), IsHtml);
                    }
                    return Content(ReturnMessage);
                }
                else
                {
                    Logger.Write("Upload Image -> Password NOT Match", "Trace");
                    return Content("Sifreyi Kontrol Ediniz.");
                }
            }
            catch (Exception ex)
            {
                Logger.Write(ErrorReturnMessage + " - " + ex, "Exception");
                return Content(ErrorReturnMessage);
            }

        }

        #endregion

    }
}
